#千锋#
一、AspectJ的五种通知方式
1、前置通知(<aop:before> @Before)
2、环绕通知(<aop:around @Around)
3、后置通知(<aop:after-returning> @AfterReturning)
4、异常通知(<aop:after-throwing> @AfterThrowing)
5、最终通知(<aop:after> @After)
二、基于xml方式配置通知类型
<aop:config proxy-target-class="true">
<aop:aspect ref="as">
<aop:pointcut id="pt" expression="execution(* com.qianfeng.aop.*.*(..))"/>
<aop:after-returning method="afterReturnning" pointcut-ref="pt" returning="obj"/>
<aop:after method="after" pointcut-ref="pt"/>
<aop:before method="before" pointcut-ref="pt"/>
<aop:around method="around" pointcut-ref="pt" />
<aop:after-throwing method="throwing" pointcut-ref="pt" throwing="e"/>
</aop:aspect>
</aop:config>
三、基于注解方式添加AOP通知
xml加入约束xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
配置自动扫描包下的类
<context:component-scan base-package="包名"/>
给上自动代理<aop:aspectj-autoproxy/>
四、基于BeanPostProcessor接口加入AOP
去实现 BeanPostProcessor接口,并重写接口中的两个默认方法,拿方法中的对象参数去执行jdk的Proxy动态代理
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("--------before---------");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("----------------------");
Object o = Proxy.newProxyInstance(MyBeanProceeor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("-------before--------");
Object obj = method.invoke(bean, args);
System.out.println("---------after------------");
return obj;
}
});
return o;
}
五、总结
切点即要增强的方法名或类
连接点即调用的原方法
通知即切面中的增强方法
切面即封装增强方法的类,增强的方法(即切点多了,点成面)。
通知最终通知after和后置通知afterReturning的区别,即后置通知是在方法成功执行后织入并将返回值返回,
最终通知则是无论方法如何结束(即使报异常)也会执行。
同一个连接点(即原方法)有多个通知执行时,前置通知和环绕前通知是未知顺序的,后置通知和环绕后通知的顺序也是未知的。
在xml配置中,前置通知和环绕前通知谁在前谁先执行,后置通知和环绕后通知(后置通知在before前,后置通知先执行,后置通知在before后,环绕后通知先执行,但加入最终通知的配置后顺序又变。当后置和和最终都在before前时两个通知都在环绕后通知之前,基本围绕跟before顺序改变才会改变)