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的更多相关文章

  1. Spring注解 - AOP 面向切面编程

    基本概念: AOP:Aspect Oriented Programming,即面向切面编程 指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式 前置通知(@Before):在目标 ...

  2. 基于spring注解AOP的异常处理

    一.前言 项目刚刚开发的时候,并没有做好充足的准备.开发到一定程度的时候才会想到还有一些问题没有解决.就比如今天我要说的一个问题:异常的处理.写程序的时候一般都会通过try...catch...fin ...

  3. Spring注解AOP及单元测试junit(6)

    2019-03-10/20:19:56 演示:将xml配置方式改为注解方式 静态以及动态代理推荐博客:https://blog.csdn.net/javazejian/article/details/ ...

  4. 重新学习Spring注解——AOP

    面向切面编程——思想:在一个地方定义通用功能,但是可以通过声明的方式定义这个功能要以何种方式在何处运用,而无须修改受影响的类. 切面:横切关注点可以被模块化为特殊的类. 优点: 1.每个关注点都集中在 ...

  5. spring注解 aop

    @Resource(name="as")  为空按类型装配 @autowired 按类型 @quafiler (name="xx") 按名称 spring继承关 ...

  6. spring 注解aop调用invoke()

    public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlAp ...

  7. 一步一步深入spring(5)--使用基于注解的spring实现 AOP

    1.要利用spring aop,至少需要添加以下jar包 使用spring需要的jarspring.jar .commons-logging.jar 使用切面编程(AOP)需要的jar aspectj ...

  8. Java框架spring 学习笔记(十四):注解aop操作

    回见Java框架spring Boot学习笔记(十三):aop实例操作,这里介绍注解aop操作 首先编写一个切入点HelloWorld.java package com.example.spring; ...

  9. Spring的AOP基于AspectJ的注解方式开发3

    上上偏博客介绍了@Aspect,@Before 上篇博客介绍了spring的AOP开发的注解通知类型:@Before,@AfterThrowing,@After,@AfterReturning,@Ar ...

随机推荐

  1. 用sticky.js实现头部导航栏固定

    在页面中,如果页面长度过大,滑动页面时,头部导航栏则会跟着划走. 我的头部导航栏代码为: <div class="headbar"> <center class= ...

  2. IT兄弟连 Java语法教程 数据类型转换

    类型转换是将一个值从一种类型更改为另一种类型的过程.例如,可以将String(字符串,字符串是Java中非常特殊的数据类型,字符串属于引用类型,但是可以像基本类型一样使用字面值赋值)类型数据“456” ...

  3. ACL学习

    H3C ACL主要有三种: 标准ACL: 2000-2999,基于源IP地址分配: 高级ACL:3000-3999,基于源目IP地址分配,报文优先级等三.四层信息: 二层ACL:4000-4999,基 ...

  4. github上星星1万多的python教程推荐收藏

    简单的说,Python是一个“优雅”.“明确”.“简单”的编程语言. 学习曲线低,非专业人士也能上手 开源系统,拥有强大的生态圈 解释型语言,完美的平台可移植性 支持面向对象和函数式编程 能够通过调用 ...

  5. Idea-搜索快捷键

    1.Ctrl+N按名字搜索类 相当于eclipse的ctrl+shift+R,输入类名可以定位到这个类文件,就像idea在其它的搜索部分的表现一样,搜索类名也能对你所要搜索的内容多个部分进行匹配,而且 ...

  6. MySQL(7)---存储过程

    Mysql(7)---存储过程 存储过程接下来会有三篇相关博客 第一篇存储过程常用语法. 第二篇存储过程中的游标. 第三篇单独讲一个实际开发过程中复杂的真实的案例. 一.概述 1.什么是存储过程 概述 ...

  7. 通过Desktop.ini设置文件夹备注以及图标

    1.新建一个文件夹temp,进入此文件夹,建立desktop.ini文件,编辑内容为: ; 文件夹图标 [.ShellClassInfo] ;设置文件夹的备注 InfoTip=this is temp ...

  8. 通过SSH通道来访问MySQL

     许多时候当要使用Mysql时,会遇到如下情况: 1. 信息比较重要,希望通信被加密.2. 一些端口,比如3306端口,被路由器禁用. 对第一个问题的一个比较直接的解决办法就是更改mysql的代码,或 ...

  9. DIY客户端框架

    C/S类型的客户端做过好多轮了,在架构上每次都调整优化一部分,慢慢的形成了DIY的框架性东西. 可是最近这一看呢,已经不像MVC了,然后有一天看到了MVP概念,咦!很像.再一看,嗯,就该是MVP. M ...

  10. split("\\,")引起的java.lang.ArrayIndexOutOfBoundsException异常解决方案

    由split("\,")引起的指标越界异常 如果字符串最后分隔符里的字段为空,使用split("\\,")进行切割时,最后的空字段不会切割 例如"a, ...