Aspect Oriented Programming
在不惊动原始设计的基础上为方法进行功能增强
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
/**
* Spring AOP defaults to using standard JDK dynamic proxies for AOP proxies.
* This enables any interface (or set of interfaces) to be proxied.
* Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are by definition not intercepted.
* For JDK proxies, only public interface method calls on the proxy can be intercepted.
* With CGLIB, public and protected method calls on the proxy will be intercepted, and even package-visible methods if necessary.
* However, common interactions through proxies should always be designed through public signatures.
*/
@Component
@Aspect // 切面类
public class MyAdvice {
// 定义切点
@Pointcut("execution(void dao.BookDao.update())") // the pointcut expression
private void pt(){} // the pointcut signature
// 具体要增强的内容, 在切点之前运行
@Before("pt()")
public void fn(){
System.out.println(System.currentTimeMillis());
}
}
@Configuration // 定义为 配置类
@EnableAspectJAutoProxy // 打开 aop注解
@ComponentScan({"dao","service","aop"})
public class SpringConfig {
}
前置通知, 在目标方法执行之前执行。
后置通知, 在目标方法执行之后执行。(如果目标方法遇到异常,则不执行通知)
异常通知, 在目标方法抛出异常时执行,可以获取异常信息。
最终通知, 在目标方法执行后执行, 无论是否遇到异常。
环绕通知, 最强大的通知类型。
环绕通知
@Around("pt()")
public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("around before advice ...");
// 表示对原始操作的调用
Object ret = pjp.proceed();
System.out.println("around after advice ...");
return ret;
}
// 原始方法返回值如果是void, 这里的通知方法返回类型可以是 void 或 Object
// 原始方法返回值如果不是 void , 这里的通知方法返回类型 必须是 Object
// Object[] args = pjp.getArgs(); // 获取原始方法的参数
通知方法在被调用时,Spring可以为其传递一些必要的参数
JoinPoint:任何通知都可使用
ProceedingJoinPoint:在环绕通知中使用
Throwable:在异常通知中使用,需要在afterThrowing注解中使用throwing指定参数名称
在xml中,一个命名空间对应一个命名空间处理器(对应jar包中的spring.handlers文件中有信息)
命名空间处理器有init方法,为不同的标签注册解析器parser
解析器实现BeanDefinitionParser接口,有一个parse方法
xml方式配置的aspect标签,对应解析器parse方法实际上是向Spring容器中注入了一个AspectJAwareAdvisorAutoProxyCreator类
AspectJAwareAdvisorAutoProxyCreator实现了BeanPostProcessor接口
AspectJAwareAdvisorAutoProxyCreator的爷爷有after方法,进行刷选bean,对要进行增强的,调用wrapIfNecessary方法,里面又调用了createProxy方法,创建目标类的代理对象,进行包装返回,最终存到单例池中的是目标类的代理对象
Aop使用了两种代理:CglibAopProxy和JdkDynamicAopProxy(默认使用,里面也是用的原生的方式创建的Proxy)
JDK动态代理使用条件,目标类有接口,生成的代理对象是接口的实现类
CGLIB动态代理使用条件,目标类无接口且不能用final修饰,生成的代理对象是目标类的子类
CGLIB proxies intercept only public method calls!
只用注解方式配置的aop,parse方法注入的是一个AnnotationAwareAspectJAutoProxyCreater,它是AspectJAwareAdvisorAutoProxyCreator的子类
SpringAOP编程官方文档解读目录
SpringAOP编程官方文档解读之切点
jdk动态代理