spring-注解---aopjava
package com.zwj.aop; import java.util.Arrays; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; /** * 切面类 * @author lfy * * @Aspect: 告诉Spring当前类是一个切面类 * */ @Aspect public class LogAspects { //抽取公共的切入点表达式 //一、本类引用 //二、其余的切面引用 @Pointcut("execution(public int com.zwj.aop.MathCalculator.*(..))") public void pointCut(){}; //@Before在目标方法以前切入;切入点表达式(指定在哪一个方法切入) @Before("pointCut()") public void logStart(JoinPoint joinPoint){ Object[] args = joinPoint.getArgs(); System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before:参数列表是:{"+Arrays.asList(args)+"}"); } @After("com.zwj.aop.LogAspects.pointCut()") public void logEnd(JoinPoint joinPoint){ System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After"); } //JoinPoint必定要出如今参数表的第一位 @AfterReturning(value="pointCut()",returning="result") public void logReturn(JoinPoint joinPoint,Object result){ System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。@AfterReturning:运行结果:{"+result+"}"); } @AfterThrowing(value="pointCut()",throwing="exception") public void logException(JoinPoint joinPoint,Exception exception){ System.out.println(""+joinPoint.getSignature().getName()+"异常。。。异常信息:{"+exception+"}"); } }
package com.zwj.aop; public class MathCalculator { public int div(int i,int j){ System.out.println("MathCalculator...div..."); return i/j; } }
package com.zwj.config; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.springframework.aop.Advisor; import org.springframework.aop.Pointcut; import org.springframework.aop.framework.AopInfrastructureBean; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import com.zwj.aop.LogAspects; import com.zwj.aop.MathCalculator; /** * AOP:【动态代理】 * 指在程序运行期间动态的将某段代码切入到指定方法指定位置进行运行的编程方式; * * 一、导入aop模块;Spring AOP:(spring-aspects) * 二、定义一个业务逻辑类(MathCalculator);在业务逻辑运行的时候将日志进行打印(方法以前、方法运行结束、方法出现异常,xxx) * 三、定义一个日志切面类(LogAspects):切面类里面的方法须要动态感知MathCalculator.div运行到哪里而后执行; * 通知方法: * 前置通知(@Before):logStart:在目标方法(div)运行以前运行 * 后置通知(@After):logEnd:在目标方法(div)运行结束以后运行(不管方法正常结束仍是异常结束) * 返回通知(@AfterReturning):logReturn:在目标方法(div)正常返回以后运行 * 异常通知(@AfterThrowing):logException:在目标方法(div)出现异常之后运行 * 环绕通知(@Around):动态代理,手动推动目标方法运行(joinPoint.procced()) * 四、给切面类的目标方法标注什么时候何地运行(通知注解); * 五、将切面类和业务逻辑类(目标方法所在类)都加入到容器中; * 六、必须告诉Spring哪一个类是切面类(给切面类上加一个注解:@Aspect) * [7]、给配置类中加 @EnableAspectJAutoProxy 【开启基于注解的aop模式】 * 在Spring中不少的 @EnableXXX; * * 三步: * 1)、将业务逻辑组件和切面类都加入到容器中;告诉Spring哪一个是切面类(@Aspect) * 2)、在切面类上的每个通知方法上标注通知注解,告诉Spring什么时候何地运行(切入点表达式) * 3)、开启基于注解的aop模式;@EnableAspectJAutoProxy * * AOP原理:【看给容器中注册了什么组件,这个组件何时工做,这个组件的功能是什么?】 * @EnableAspectJAutoProxy; * 一、@EnableAspectJAutoProxy是什么? * @Import(AspectJAutoProxyRegistrar.class):给容器中导入AspectJAutoProxyRegistrar * 利用AspectJAutoProxyRegistrar自定义给容器中注册bean;BeanDefinetion * internalAutoProxyCreator=AnnotationAwareAspectJAutoProxyCreator * * 给容器中注册一个AnnotationAwareAspectJAutoProxyCreator; * * 二、 AnnotationAwareAspectJAutoProxyCreator: * AnnotationAwareAspectJAutoProxyCreator * ->AspectJAwareAdvisorAutoProxyCreator * ->AbstractAdvisorAutoProxyCreator * ->AbstractAutoProxyCreator * implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware * 关注后置处理器(在bean初始化完成先后作事情)、自动装配BeanFactory * * AbstractAutoProxyCreator.setBeanFactory() * AbstractAutoProxyCreator.有后置处理器的逻辑; * * AbstractAdvisorAutoProxyCreator.setBeanFactory()-》initBeanFactory() * * AnnotationAwareAspectJAutoProxyCreator.initBeanFactory() * * * 流程: * 1)、传入配置类,建立ioc容器 * 2)、注册配置类,调用refresh()刷新容器; * 3)、registerBeanPostProcessors(beanFactory);注册bean的后置处理器来方便拦截bean的建立; * 1)、先获取ioc容器已经定义了的须要建立对象的全部BeanPostProcessor * 2)、给容器中加别的BeanPostProcessor * 3)、优先注册实现了PriorityOrdered接口的BeanPostProcessor; * 4)、再给容器中注册实现了Ordered接口的BeanPostProcessor; * 5)、注册没实现优先级接口的BeanPostProcessor; * 6)、注册BeanPostProcessor,实际上就是建立BeanPostProcessor对象,保存在容器中; * 建立internalAutoProxyCreator的BeanPostProcessor【AnnotationAwareAspectJAutoProxyCreator】 * 1)、建立Bean的实例 * 2)、populateBean;给bean的各类属性赋值 * 3)、initializeBean:初始化bean; * 1)、invokeAwareMethods():处理Aware接口的方法回调 * 2)、applyBeanPostProcessorsBeforeInitialization():应用后置处理器的postProcessBeforeInitialization() * 3)、invokeInitMethods();执行自定义的初始化方法 * 4)、applyBeanPostProcessorsAfterInitialization();执行后置处理器的postProcessAfterInitialization(); * 4)、BeanPostProcessor(AnnotationAwareAspectJAutoProxyCreator)建立成功;--》aspectJAdvisorsBuilder * 7)、把BeanPostProcessor注册到BeanFactory中; * beanFactory.addBeanPostProcessor(postProcessor); * =======以上是建立和注册AnnotationAwareAspectJAutoProxyCreator的过程======== * * AnnotationAwareAspectJAutoProxyCreator => InstantiationAwareBeanPostProcessor * 4)、finishBeanFactoryInitialization(beanFactory);完成BeanFactory初始化工做;建立剩下的单实例bean * 1)、遍历获取容器中全部的Bean,依次建立对象getBean(beanName); * getBean->doGetBean()->getSingleton()-> * 2)、建立bean * 【AnnotationAwareAspectJAutoProxyCreator在全部bean建立以前会有一个拦截,InstantiationAwareBeanPostProcessor,会调用postProcessBeforeInstantiation()】 * 1)、先从缓存中获取当前bean,若是能获取到,说明bean是以前被建立过的,直接使用,不然再建立; * 只要建立好的Bean都会被缓存起来 * 2)、createBean();建立bean; * AnnotationAwareAspectJAutoProxyCreator 会在任何bean建立以前先尝试返回bean的实例 * 【BeanPostProcessor是在Bean对象建立完成初始化先后调用的】 * 【InstantiationAwareBeanPostProcessor是在建立Bean实例以前先尝试用后置处理器返回对象的】 * 1)、resolveBeforeInstantiation(beanName, mbdToUse);解析BeforeInstantiation * 但愿后置处理器在此能返回一个代理对象;若是能返回代理对象就使用,若是不能就继续 * 1)、后置处理器先尝试返回对象; * bean = applyBeanPostProcessorsBeforeInstantiation(): * 拿到全部后置处理器,若是是InstantiationAwareBeanPostProcessor; * 就执行postProcessBeforeInstantiation * if (bean != null) { bean = applyBeanPostProcessorsAfterInitialization(bean, beanName); } * * 2)、doCreateBean(beanName, mbdToUse, args);真正的去建立一个bean实例;和3.6流程同样; * 3)、 * * * AnnotationAwareAspectJAutoProxyCreator【InstantiationAwareBeanPostProcessor】 的做用: * 1)、每个bean建立以前,调用postProcessBeforeInstantiation(); * 关心MathCalculator和LogAspect的建立 * 1)、判断当前bean是否在advisedBeans中(保存了全部须要加强bean) * 2)、判断当前bean是不是基础类型的Advice、Pointcut、Advisor、AopInfrastructureBean, * 或者是不是切面(@Aspect) * 3)、是否须要跳过 * 1)、获取候选的加强器(切面里面的通知方法)【List<Advisor> candidateAdvisors】 * 每个封装的通知方法的加强器是 InstantiationModelAwarePointcutAdvisor; * 判断每个加强器是不是 AspectJPointcutAdvisor 类型的;返回true * 2)、永远返回false * * 2)、建立对象 * postProcessAfterInitialization; * return wrapIfNecessary(bean, beanName, cacheKey);//包装若是须要的状况下 * 1)、获取当前bean的全部加强器(通知方法) Object[] specificInterceptors * 一、找到候选的全部的加强器(找哪些通知方法是须要切入当前bean方法的) * 二、获取到能在bean使用的加强器。 * 三、给加强器排序 * 2)、保存当前bean在advisedBeans中; * 3)、若是当前bean须要加强,建立当前bean的代理对象; * 1)、获取全部加强器(通知方法) * 2)、保存到proxyFactory * 3)、建立代理对象:Spring自动决定 * JdkDynamicAopProxy(config);jdk动态代理; * ObjenesisCglibAopProxy(config);cglib的动态代理; * 4)、给容器中返回当前组件使用cglib加强了的代理对象; * 5)、之后容器中获取到的就是这个组件的代理对象,执行目标方法的时候,代理对象就会执行通知方法的流程; * * * 3)、目标方法执行 ; * 容器中保存了组件的代理对象(cglib加强后的对象),这个对象里面保存了详细信息(好比加强器,目标对象,xxx); * 1)、CglibAopProxy.intercept();拦截目标方法的执行 * 2)、根据ProxyFactory对象获取将要执行的目标方法拦截器链; * List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass); * 1)、List<Object> interceptorList保存全部拦截器 5 * 一个默认的ExposeInvocationInterceptor 和 4个加强器; * 2)、遍历全部的加强器,将其转为Interceptor; * registry.getInterceptors(advisor); * 3)、将加强器转为List<MethodInterceptor>; * 若是是MethodInterceptor,直接加入到集合中 * 若是不是,使用AdvisorAdapter将加强器转为MethodInterceptor; * 转换完成返回MethodInterceptor数组; * * 3)、若是没有拦截器链,直接执行目标方法; * 拦截器链(每个通知方法又被包装为方法拦截器,利用MethodInterceptor机制) * 4)、若是有拦截器链,把须要执行的目标对象,目标方法, * 拦截器链等信息传入建立一个 CglibMethodInvocation 对象, * 并调用 Object retVal = mi.proceed(); * 5)、拦截器链的触发过程; * 1)、若是没有拦截器执行执行目标方法,或者拦截器的索引和拦截器数组-1大小同样(指定到了最后一个拦截器)执行目标方法; * 2)、链式获取每个拦截器,拦截器执行invoke方法,每个拦截器等待下一个拦截器执行完成返回之后再来执行; * 拦截器链的机制,保证通知方法与目标方法的执行顺序; * * 总结: * 1)、 @EnableAspectJAutoProxy 开启AOP功能 * 2)、 @EnableAspectJAutoProxy 会给容器中注册一个组件 AnnotationAwareAspectJAutoProxyCreator * 3)、AnnotationAwareAspectJAutoProxyCreator是一个后置处理器; * 4)、容器的建立流程: * 1)、registerBeanPostProcessors()注册后置处理器;建立AnnotationAwareAspectJAutoProxyCreator对象 * 2)、finishBeanFactoryInitialization()初始化剩下的单实例bean * 1)、建立业务逻辑组件和切面组件 * 2)、AnnotationAwareAspectJAutoProxyCreator拦截组件的建立过程 * 3)、组件建立完以后,判断组件是否须要加强 * 是:切面的通知方法,包装成加强器(Advisor);给业务逻辑组件建立一个代理对象(cglib); * 5)、执行目标方法: * 1)、代理对象执行目标方法 * 2)、CglibAopProxy.intercept(); * 1)、获得目标方法的拦截器链(加强器包装成拦截器MethodInterceptor) * 2)、利用拦截器的链式机制,依次进入每个拦截器进行执行; * 3)、效果: * 正常执行:前置通知-》目标方法-》后置通知-》返回通知 * 出现异常:前置通知-》目标方法-》后置通知-》异常通知 * * * */ @EnableAspectJAutoProxy @Configuration public class MainConfigOfAOP { //业务逻辑类加入容器中 @Bean public MathCalculator calculator(){ return new MathCalculator(); } //切面类加入到容器中 @Bean public LogAspects logAspects(){ return new LogAspects(); } }
package com.zwj.test; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.zwj.aop.MathCalculator; import com.zwj.config.MainConfigOfAOP; public class IOCTest_AOP { @Test public void test01(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAOP.class); //一、不要本身建立对象 // MathCalculator mathCalculator = new MathCalculator(); // mathCalculator.div(1, 1); MathCalculator mathCalculator = applicationContext.getBean(MathCalculator.class); mathCalculator.div(1, 0); applicationContext.close(); } }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zwj</groupId> <artifactId>spring-annotation---AOP</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-context --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.12.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.12.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/javax.inject/javax.inject --> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> </dependency> </dependencies> </project>
div运行。。。@Before:参数列表是:{[1, 0]}
MathCalculator...div...
div结束。。。@After
div异常。。。异常信息:{java.lang.ArithmeticException: / by zero}
mysql