spring 注解AOP
aspectAnnotation的切面信息,加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
解析annotationServiceImpl的时候(此时AspectAnnotation还没有解析),resolveBeforeInstantiation方法里面shouldSkip方法里面,会去spring的容器找所有有Aspect注解的类,找到aspectAnnotation,然后把aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
然后在doCreateBean方法里面的initializeBean方法里面的applyBeanPostProcessorsAfterInitialization方法里面,返回jdk的动态代理:org.springframework.aop.framework.JdkDynamicAopProxy@5933aa7e,代理的 h = jdk动态代理,代理的ProxyFactory里面有AnnotationServiceImpl和切面[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
<aop:aspectj-autoproxy/> 有这个标签才支持注解。
@Service //首先要是一个bean,然后再是反射拿到Aspect注解。
@Aspect
public class AspectAnnotation {//注解针对的是spring所有的bean。只要满足注解条件。 @Pointcut("execution(public * com.zhuguang.jack.annotation.*.*(..))")
//拦截的方法:com.zhuguang.jack.service.*.* 包下的任意方法。
//(一个类的接口在这个包下面,实现类不在这个包下面,也属于条件符合)
//(实现类在这个包下面,接口不在这个包下面,也属于符合条件)
public void pc1(){} @Before("pc1()")
public void beforeee(JoinPoint joinPoint) {
System.out.println("==============beforeee 前置通知=========");
} @After("pc1()")
public void afterrr(JoinPoint joinPoint) {
System.out.println("==============afterrr 后置通知=========");
} @Around("pc1()")
public void arounddd(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("==============arounddd 前置通知=========");
joinPoint.proceed();
System.out.println("==============arounddd 后置通知=========");
} }
public interface MyService {
public String doSomething(String param);
public String throwTest(String param);
}
@Service("annotationServiceImpl")
public class AnnotationServiceImpl {
public String doSomething(String param) {
System.out.println("==========AnnotationServiceImpl.doSomething=========");
}
}
public class Test2 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath*:config" + "/spring/applicationContext-core2.xml");
AnnotationServiceImpl as = (AnnotationServiceImpl) context.getBean("annotationServiceImpl");
as.doSomething("Jack"); //aop起作用
}
}
==============arounddd 前置通知=========
==============beforeee 前置通知=========
==========AnnotationServiceImpl.doSomething=========
==============arounddd 后置通知=========
==============afterrr 后置通知=========
applicationContext-core2.xml (只有一个扫描,和开启aop注解)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:util="http://www.springframework.org/schema/util" xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"
default-lazy-init="true"> <context:component-scan base-package="com.zhuguang.jack"
use-default-filters="true" annotation-config="true">
</context:component-scan> <aop:aspectj-autoproxy/>
</beans>
解析<aop:aspectj-autoproxy/>标签:
public class AopNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("aspectj-autoproxy", new AspectJAutoProxyBeanDefinitionParser());
}
}
public BeanDefinition parse(Element element, ParserContext parserContext) { //element = [aop:aspectj-autoproxy: null],
AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element); //注册入口类,AnnotationAwareAspectJAutoProxyCreator.class,放到spring的容器。
extendBeanDefinition(element, parserContext);
return null;
}
xml配置aop的时候,还要解析aspect,pointcut,advisor,before,after,after-returning,around然后解析成beanDefinition加到spring的容器中去。 注解版的,只需要把<aop:aspectj-autoproxy/>标签解析成AnnotationAwareAspectJAutoProxyCreator的beanDefinition然后加到容器中去就可以了。
aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //解析apploication-core.xml文件,现在总共加了7个beandefiniton到spring的容器中,把xml文件里面的bean还有spring自己的bean都加到spring的容器中去了。
protected final void refreshBeanFactory() throws BeansException {
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = getResourceLoader(); //ClassPathXmlApplicationContext@399c4be1,
if (resourceLoader instanceof ResourcePatternResolver) {
try {
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
int loadCount = loadBeanDefinitions(resources); //resources = spring-source-web-master/target/classes/config/spring/applicationContext-core2.xml,
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
try {
InputStream inputStream = encodedResource.getResource().getInputStream(); //spring-source-web-master\spring-source-web-master\target\classes\config\spring\applicationContext-core2.xml
try {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
Document doc = doLoadDocument(inputSource, resource); //spring-source-web-master/spring-source-web-master/target/classes/config/spring/applicationContext-core2.xml doc = [context:component-scan: null], [aop:aspectj-autoproxy: null]]
return registerBeanDefinitions(doc, resource);
}
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware); //DocumentBuilderFactoryImpl
DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler); //DocumentBuilderImpl
return builder.parse(inputSource); //spring-source-web-master\target\classes\config\spring\applicationContext-core2.xml
}
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader(); //DefaultBeanDefinitionDocumentReader
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
}
protected void doRegisterBeanDefinitions(Element root) {
preProcessXml(root);
parseBeanDefinitions(root, this.delegate); //root = applicationCore.xml的根<beans>标签,
postProcessXml(root);
}
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes(); //便利applicationCore.xml的根节点的所有子节点,
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
else {
delegate.parseCustomElement(ele); //解析自定义的context:component-scan标签,aop:aspectj-autoproxy标签,
}
}
}
}
}
//解析自定义的context:component-scan标签 public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
String namespaceUri = getNamespaceURI(ele); //http://www.springframework.org/schema/context,
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd)); //handler = ContextNamespaceHandler,ele = context:component-scan,
}
public NamespaceHandler resolve(String namespaceUri) {
else {
String className = (String) handlerOrClassName;
try {
Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass); //ContextNamespaceHandler,是一个NamespaceHandler
namespaceHandler.init();
handlerMappings.put(namespaceUri, namespaceHandler);
return namespaceHandler;
}
}
}
public class ContextNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser()); //解析context:component-sca标签的类加到ContextNamespaceHandler 进去
}
}
public BeanDefinition parse(Element element, ParserContext parserContext) {
return findParserForElement(element, parserContext).parse(element, parserContext); //根据element = context:component-scan找到这个标签对应的解析类ComponentScanBeanDefinitionParser,
}
public BeanDefinition parse(Element element, ParserContext parserContext) {
String[] basePackages = StringUtils.tokenizeToStringArray(element.getAttribute(BASE_PACKAGE_ATTRIBUTE),
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); //[com.zhuguang.jack] // Actually scan for bean definitions and register them.
ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, element); //ClassPathBeanDefinitionScanner
Set<BeanDefinitionHolder> beanDefinitions = scanner.doScan(basePackages); //aspectAnnotation,annotationServiceImpl这2个bean的定义,加到spring容器中去,
registerComponents(parserContext.getReaderContext(), beanDefinitions, element); return null;
}
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
for (String basePackage : basePackages) {
Set<BeanDefinition> candidates = findCandidateComponents(basePackage); //这个包下面只有2个类要解析,[class [AnnotationServiceImpl];spring-source-web-master\target\classes\com\zhuguang\jack\annotation\AnnotationServiceImpl.class],
[AspectAnnotation];spring-source-web-master\target\classes\com\zhuguang\jack\annotation\AspectAnnotation.class]]
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
registerBeanDefinition(definitionHolder, this.registry); //aspectAnnotation,annotationServiceImpl这2个bean的定义,加到spring容器中去,
}
}
}
return beanDefinitions;
}
protected void registerComponents(
XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {
if (annotationConfig) {
Set<BeanDefinitionHolder> processorDefinitions =
AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source); //加了4个bean到spring的容器[CommonAnnotationBeanPostProcessor]; [ConfigurationClassPostProcessor]; [RequiredAnnotationBeanPostProcessor]; [AutowiredAnnotationBeanPostProcessor]; 是注解配置的处理器。
for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
}
} readerContext.fireComponentRegistered(compositeDef);
}
解析aop:aspectj-autoproxy标签:
public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
String namespaceUri = getNamespaceURI(ele); //http://www.springframework.org/schema/aop
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}
public NamespaceHandler resolve(String namespaceUri) {
else {
String className = (String) handlerOrClassName;
try {
Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass); //AopNamespaceHandler,是一个NamespaceHandler
namespaceHandler.init();
handlerMappings.put(namespaceUri, namespaceHandler);
return namespaceHandler;
}
}
}
public BeanDefinition parse(Element element, ParserContext parserContext) {
return findParserForElement(element, parserContext).parse(element, parserContext); //找到aop:aspectj-autoproxy对应的解析器AspectJAutoProxyBeanDefinitionParser,
}
public BeanDefinition parse(Element element, ParserContext parserContext) {
AopNamespaceUtils.registerAspectJAnnotationAutoProxyCreatorIfNecessary(parserContext, element); //AnnotationAwareAspectJAutoProxyCreator的bean定义加到spring的容器,
extendBeanDefinition(element, parserContext);
return null;
}
现在总共加了7个beandefiniton到spring的容器中
CommonAnnotationBeanPostProcessor; ConfigurationClassPostProcessor; RequiredAnnotationBeanPostProcessor;AutowiredAnnotationBeanPostProcessor;(这4个是spring自己加的)。
AspectAnnotation;(component-scan出的自己写的类)
AnnotationServiceImpl;(component-scan出的自己写的类)
AnnotationAwareAspectJAutoProxyCreator;(<aop:aspectj-autoproxy/>标签对应的beanDefinition)
registerBeanPostProcessors(beanFactory);
实例化实现了BeanPostProcessor接口的6个bean:[internalAutowiredAnnotationProcessor, internalRequiredAnnotationProcessor, internalCommonAnnotationProcessor, internalAutoProxyCreator, ConfigurationClassPostProcessor.importAwareProcessor, ConfigurationClassPostProcessor.enhancedConfigurationProcessor]
finishBeanFactoryInitialization(beanFactory);
beanFactory.preInstantiateSingletons();
//实例化9个bean,[annotationServiceImpl, aspectAnnotation, (没有解析成bean实例)。internalConfigurationAnnotationProcessor, internalAutowiredAnnotationProcessor, internalRequiredAnnotationProcessor, internalCommonAnnotationProcessor, internalAutoProxyCreator, ConfigurationClassPostProcessor.importAwareProcessor, ConfigurationClassPostProcessor.enhancedConfigurationProcessor(已经解析成实例了)。
解析annotationServiceImpl (里面有切面的类,先解析的这个类)
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
try {
Object bean = resolveBeforeInstantiation(beanName, mbd); //null。aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
if (bean != null) {
return bean;
}
}
Object beanInstance = doCreateBean(beanName, mbd, args);
return beanInstance;//返回jdk的动态代理,org.springframework.aop.framework.JdkDynamicAopProxy@5933aa7e,代理的h = jdk动态代理,代理的ProxyFactory里面有AnnotationServiceImpl和切面[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
}
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName); //null,aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName){
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName); //ConfigurationClassPostProcessor.enhancedConfigurationProcessor(没做什么事),CommonAnnotationBeanPostProcessor(没做什么事),AutowiredAnnotationBeanPostProcessor(没做什么事),RequiredAnnotationBeanPostProcessor(没做什么事),AnnotationAwareAspectJAutoProxyCreator(<aop:aspectj-autoproxy/>标签对应的beanDefinition),aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
if (result != null) {
return result;
}
}
}
return null;
}
AnnotationAwareAspectJAutoProxyCreator(<aop:aspectj-autoproxy/>标签对应的beanDefinition)的postProcessBeforeInstantiation方法。
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { //aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
if (beanName != null) {
TargetSource targetSource = getCustomTargetSource(beanClass, beanName); //null就什么都不做。
if (targetSource != null) {
this.targetSourcedBeans.add(beanName);
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
}
return null;
}
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
List<Advisor> candidateAdvisors = findCandidateAdvisors(); //aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
for (Advisor advisor : candidateAdvisors) {
if (advisor instanceof AspectJPointcutAdvisor) {
if (((AbstractAspectJAdvice) advisor.getAdvice()).getAspectName().equals(beanName)) { //一个都不是
return true;
}
}
}
return super.shouldSkip(beanClass, beanName);
}
protected List<Advisor> findCandidateAdvisors() {
List<Advisor> advisors = super.findCandidateAdvisors(); //null
advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors()); //this = AnnotationAwareAspectJAutoProxyCreator,aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
return advisors;
}
public List<Advisor> buildAspectJAdvisors() { //第二次从缓存advisorsCache中获取。
List<String> aspectNames = null;
synchronized (this) {
aspectNames = this.aspectBeanNames;
if (aspectNames == null) {
List<Advisor> advisors = new LinkedList<Advisor>();
aspectNames = new LinkedList<String>();
String[] beanNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(this.beanFactory, Object.class, true, false); //拿到spring容器所有的Object.class,就是所有的bean,
for (String beanName : beanNames) {
if (this.advisorFactory.isAspect(beanType)) { //有没有Aspect注解,aspectAnnotation有这个注解,
aspectNames.add(beanName);
AspectMetadata amd = new AspectMetadata(beanType, beanName);
if (amd.getAjType().getPerClause().getKind() == PerClauseKind.SINGLETON) {
MetadataAwareAspectInstanceFactory factory =
new BeanFactoryAspectInstanceFactory(this.beanFactory, beanName);
List<Advisor> classAdvisors = this.advisorFactory.getAdvisors(factory); //拿到aspectAnnotation的所有切面,
if (this.beanFactory.isSingleton(beanName)) {
this.advisorsCache.put(beanName, classAdvisors); ////this = AnnotationAwareAspectJAutoProxyCreator,aspectAnnotation的切面信息,就加到了AnnotationAwareAspectJAutoProxyCreator的advisorsCache属性里面去了。
}
advisors.addAll(classAdvisors);
}
}
}
this.aspectBeanNames = aspectNames;
return advisors; // [expression [pc1()];
//advice method [public void arounddd(ProceedingJoinPoint) ]; expression [pc1()];
//advice method [public beforeee(JoinPoint)]; expression [pc1()];
//advice method [public void afterrr(JoinPoint)]; ]
}
}
}
public static String[] beanNamesForTypeIncludingAncestors(
ListableBeanFactory lbf, Class<?> type, boolean includeNonSingletons, boolean allowEagerInit) {
String[] result = lbf.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); //拿到spring容器所有的Object.class,就是所有的bean,lbf是bean工厂。
return result;
}
public List<Advisor> getAdvisors(MetadataAwareAspectInstanceFactory maaif) {
final Class<?> aspectClass = maaif.getAspectMetadata().getAspectClass(); //class com.zhuguang.jack.annotation.AspectAnnotation
final String aspectName = maaif.getAspectMetadata().getAspectName(); //aspectAnnotation
final List<Advisor> advisors = new LinkedList<Advisor>();
for (Method method : getAdvisorMethods(aspectClass)) { //[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
Advisor advisor = getAdvisor(method, lazySingletonAspectInstanceFactory, advisors.size(), aspectName);
if (advisor != null) {
advisors.add(advisor);
}
}
return advisors; // [expression [pc1()];
advice method [public void arounddd(ProceedingJoinPoint) ]; expression [pc1()];
advice method [public beforeee(JoinPoint)]; expression [pc1()];
advice method [public void afterrr(JoinPoint)]; ]
}
private List<Method> getAdvisorMethods(Class<?> aspectClass) {
final List<Method> methods = new LinkedList<Method>();
ReflectionUtils.doWithMethods(aspectClass, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException {
// 没有@Pointcut注解的方法,加进去,@Pointcut不要,只处理@before,@after,@around。
if (AnnotationUtils.getAnnotation(method, Pointcut.class) == null) {
methods.add(method);
}
}
});
Collections.sort(methods, METHOD_COMPARATOR);
return methods; //拿到所有的方法
//[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],包括父类的方法。
}
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf) {
Method[] methods = clazz.getDeclaredMethods(); //拿到所有的方法,
for (Method method : methods) {
try {
mc.doWith(method);
}
}
if (clazz.getSuperclass() != null) {
doWithMethods(clazz.getSuperclass(), mc, mf); //父类
}
}
public Advisor getAdvisor(Method candidateAdviceMethod, MetadataAwareAspectInstanceFactory aif,
int declarationOrderInAspect, String aspectName) {//[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
AspectJExpressionPointcut ajexp =
getPointcut(candidateAdviceMethod, aif.getAspectMetadata().getAspectClass());
return new InstantiationModelAwarePointcutAdvisorImpl(
this, ajexp, aif, candidateAdviceMethod, declarationOrderInAspect, aspectName);
}
private AspectJExpressionPointcut getPointcut(Method candidateAdviceMethod, Class<?> candidateAspectClass) {
AspectJAnnotation<?> aspectJAnnotation =
AbstractAspectJAdvisorFactory.findAspectJAnnotationOnMethod(candidateAdviceMethod);//方法上面是否有@before,@after,@around注解,就包装有这些注解的方法。
AspectJExpressionPointcut ajexp =
new AspectJExpressionPointcut(candidateAspectClass, new String[0], new Class<?>[0]);
ajexp.setExpression(aspectJAnnotation.getPointcutExpression()); //@Expression表达式,
return ajexp;
}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
return exposedObject;//返回jdk的动态代理,org.springframework.aop.framework.JdkDynamicAopProxy@5933aa7e,代理的h = jdk动态代理,代理的ProxyFactory里面有AnnotationServiceImpl和切面[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
}
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;//返回jdk的动态代理,org.springframework.aop.framework.JdkDynamicAopProxy@5933aa7e,代理的h = jdk动态代理,代理的ProxyFactory里面有AnnotationServiceImpl和切面[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName){
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName); //AnnotationAwareAspectJAutoProxyCreator
if (result == null) {
return result;
}
}
return result;
}
//AnnotationAwareAspectJAutoProxyCreator类:
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;//返回jdk的动态代理,org.springframework.aop.framework.JdkDynamicAopProxy@5933aa7e,代理的h = jdk动态代理,代理的ProxyFactory里面有AnnotationServiceImpl和切面[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); //[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()]
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE); //加到AnnotationAwareAspectJAutoProxyCreator 的advisedBeans属性 = true,
Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); //返回jdk的动态代理,org.springframework.aop.framework.JdkDynamicAopProxy@5933aa7e,代理的h = jdk动态代理,代理的ProxyFactory里面有AnnotationServiceImpl和切面[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
protected boolean shouldSkip(Class<?> beanClass, String beanName) {
List<Advisor> candidateAdvisors = findCandidateAdvisors();// [expression [pc1()];
advice method [public void arounddd(ProceedingJoinPoint) ]; expression [pc1()];
advice method [public beforeee(JoinPoint)]; expression [pc1()];
advice method [public void afterrr(JoinPoint)]; ]
for (Advisor advisor : candidateAdvisors) {
if (advisor instanceof AspectJPointcutAdvisor) {
if (((AbstractAspectJAdvice) advisor.getAdvice()).getAspectName().equals(beanName)) { //一个都不进去
return true;
}
}
}
return super.shouldSkip(beanClass, beanName);
}
protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
return advisors.toArray();
}
protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
List<Advisor> candidateAdvisors = findCandidateAdvisors(); //[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()]
List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName); //[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()]
extendAdvisors(eligibleAdvisors);
if (!eligibleAdvisors.isEmpty()) {
eligibleAdvisors = sortAdvisors(eligibleAdvisors);
}
return eligibleAdvisors;
}
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) { //[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()]
boolean hasIntroductions = !eligibleAdvisors.isEmpty();
for (Advisor candidate : candidateAdvisors) {
if (canApply(candidate, clazz, hasIntroductions)) {
eligibleAdvisors.add(candidate);
}
}
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) { //pc = AspectJExpressionPointcut: () pc1(),pointCut对象,
MethodMatcher methodMatcher = pc.getMethodMatcher(); //AspectJExpressionPointcut: () pc1() :@Pointcut("execution(public * com.zhuguang.jack.annotation.*.*(..))")
Set<Class<?>> classes = new HashSet<Class<?>>(ClassUtils.getAllInterfacesForClassAsSet(targetClass)); //[class com.zhuguang.jack.annotation.AnnotationServiceImpl]
classes.add(targetClass);
for (Class<?> clazz : classes) {
Method[] methods = clazz.getMethods(); //这个类所有的方法,
public AnnotationServiceImpl.throwTest(String), public AnnotationServiceImpl.doSomething(String)
for (Method method : methods) { //根据@Pointcut("execution(public * com.zhuguang.jack.annotation.*.*(..))") 表达式,决定这个类的这个方法要不要拦截。
if ((introductionAwareMethodMatcher != null &&
introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
methodMatcher.matches(method, targetClass)) { //把类和方法都传进去,先匹配类在匹配方法。
return true;
}
}
}
return false;
}
protected Object createProxy(Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) { //annotationServiceImpl创建动态代理,specificInterceptors = [public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
ProxyFactory proxyFactory = new ProxyFactory(); //创建一个代理工厂,
proxyFactory.copyFrom(this); //AnnotationAwareAspectJAutoProxyCreator
Advisor[] advisors = buildAdvisors(beanName, specificInterceptors); //包装成[public void arounddd(ProceedingJoinPoint) , public void beforeee(JoinPoint), public void afterrr(JoinPoint), public void pc1()],
for (Advisor advisor : advisors) {
proxyFactory.addAdvisor(advisor); //把切面加到代理工厂,
}
proxyFactory.setTargetSource(targetSource); //设置被代理类AnnotationServiceImpl
proxyFactory.setFrozen(this.freezeProxy);
if (advisorsPreFiltered()) {
proxyFactory.setPreFiltered(true);
}
return proxyFactory.getProxy(this.proxyClassLoader); //AppClassLoader
}
public Object getProxy(ClassLoader classLoader) {
return createAopProxy().getProxy(classLoader);
}
protected final synchronized AopProxy createAopProxy() {
return getAopProxyFactory().createAopProxy(this);
}
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
Class<?> targetClass = config.getTargetClass();
if (targetClass.isInterface()) { //AnnotationServiceImpl要实现了接口,才会使用jdk的动态代理。jdk一定要有接口。
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
}
else {
return new JdkDynamicAopProxy(config);
}
}
public Object getProxy(ClassLoader classLoader) {
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised); //this = JdkDynamicAopProxy,advised = ProxyFactory,
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces); //[interface com.zhuguang.jack.annotation.MyService, interface org.springframework.aop.SpringProxy, interface org.springframework.aop.framework.Advised]
return Proxy.newProxyInstance(classLoader, proxiedInterfaces, this); //this = JdkDynamicAopProxy,
}
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces, InvocationHandler h){
Class<?> cl = getProxyClass0(loader, intfs);
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
return cons.newInstance(new Object[]{h});
}
解析AspectAnnotation(切面类)
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
try {
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
}
Object beanInstance = doCreateBean(beanName, mbd, args);
return beanInstance;
}
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
if (mbd.hasBeanClass() && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
bean = applyBeanPostProcessorsBeforeInstantiation(mbd.getBeanClass(), beanName); //AnnotationAwareAspectJAutoProxyCreator 类
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
Object cacheKey = getCacheKey(beanClass, beanName); if (beanName == null || !this.targetSourcedBeans.contains(beanName)) {
if (this.advisedBeans.containsKey(cacheKey)) {
return null;
}
if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { //有Aspect注解,不走了。
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return null;
}
}
}
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); //什么都没做
} if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException { Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName); //AnnotationAwareAspectJAutoProxyCreator 类
if (result == null) {
return result;
}
}
return result;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
if (beanName != null && this.targetSourcedBeans.contains(beanName)) {
return bean;
}
if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { //从这里返回
return bean;
}
if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
} // Create proxy if we have advice.
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
Object proxy = createProxy(bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
} this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
spring 注解AOP的更多相关文章
- Spring注解 - AOP 面向切面编程
基本概念: AOP:Aspect Oriented Programming,即面向切面编程 指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式 前置通知(@Before):在目标 ...
- 基于spring注解AOP的异常处理
一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...
- Spring注解AOP及单元测试junit(6)
2019-03-10/20:19:56 演示:将xml配置方式改为注解方式 静态以及动态代理推荐博客:https://blog.csdn.net/javazejian/article/details/ ...
- 重新学习Spring注解——AOP
面向切面编程——思想:在一个地方定义通用功能,但是可以通过声明的方式定义这个功能要以何种方式在何处运用,而无须修改受影响的类. 切面:横切关注点可以被模块化为特殊的类. 优点: 1.每个关注点都集中在 ...
- spring注解 aop
@Resource(name="as") 为空按类型装配 @autowired 按类型 @quafiler (name="xx") 按名称 spring继承关 ...
- spring 注解aop调用invoke()
public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlAp ...
- 一步一步深入spring(5)--使用基于注解的spring实现 AOP
1.要利用spring aop,至少需要添加以下jar包 使用spring需要的jarspring.jar .commons-logging.jar 使用切面编程(AOP)需要的jar aspectj ...
- Java框架spring 学习笔记(十四):注解aop操作
回见Java框架spring Boot学习笔记(十三):aop实例操作,这里介绍注解aop操作 首先编写一个切入点HelloWorld.java package com.example.spring; ...
- Spring的AOP基于AspectJ的注解方式开发3
上上偏博客介绍了@Aspect,@Before 上篇博客介绍了spring的AOP开发的注解通知类型:@Before,@AfterThrowing,@After,@AfterReturning,@Ar ...
随机推荐
- IT兄弟连 HTML5教程 HTML5和CSS3的关系
HTML5是第五版HTML的标准,CSS3则是第三版CSS,新增一些非常实用的选择器和样式属性,并且CSS3语言开发是朝着模块化发展的.以前的规范作为一个模块实在是太庞大而且比较复杂,所以,把它分解为 ...
- module.exports与exports,export与export default的区别
首先我们要明白一个前提,CommonJS模块规范和ES6模块规范完全是两种不同的概念. CommonJS模块规范 Node应用由模块组成,采用CommonJS模块规范. 根据这个规范,每个文件就是一个 ...
- Distilling the Knowledge in a Neural Network
url: https://arxiv.org/abs/1503.02531 year: NIPS 2014   简介 将大模型的泛化能力转移到小模型的一种显而易见的方法是使用由大模型产生的类概率作 ...
- jenkins支持git分支发布
https://blog.csdn.net/wc1695040842/article/details/102228804 核心就是需要安装一个Git Parameter 的插件结合使用. 如果同时有多 ...
- 【LOJ#575】【LNR#2】不等关系(容斥,动态规划,分治FFT)
[LOJ#575][LNR#2]不等关系(容斥,动态规划,分治FFT) 题面 LOJ 题解 一个暴力\(dp\),设\(f[i][j]\)表示考虑完了前\(i\)个位置,其中最后一个数在前面所有数中排 ...
- TCP协议 - 面向连接
一.TCP特性概览 1.面向连接 TCP是基于连接进行数据交互,通信双方在进行数据交互之前需要建立连接,该连接也只能用在双方之间进行交互.这点不像UDP中的组播和广播,可以在同一组中多个主机交互数据. ...
- Python爬取上交所一年大盘数据
前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: 半个码农2018 PS:如有需要Python学习资料的小伙伴可以加点 ...
- liunx简单命令
mysql -h主机地址 -u用户名 -p用户密码 --进入数据库1.显示数据库列表. show databases; 2.显示库中的数据表: use mysql: //打开库 show tables ...
- 移动应用性能测试剖析以及PerfDog与其他工具的对比分析11.22
商业转载请联系腾讯WeTest获得授权,非商业转载请注明出处. 导语: 在IT.互联网及游戏行业,软件测试都是一个重要且不可或缺的过程,测试是软件生命周期中的一个重要阶段,是软件质量保证的关键步骤.目 ...
- 解决sublime快捷键回车换行问题
鼠标右键sublime 以管理员身份运行 打开首选项里面的按键绑定用户 将下面的代码粘贴复制 { "keys": ["enter"], "comman ...