首先,附上原理图

1.大概介绍
AOP 即面向切面编程
- 切面(aspect):
横切面对象,一般为一个具体类对象(可以借助@Aspect声明)- 连接点(joinpoint): 程序执行过程中某个特定的点,一般指被拦截到的的方法
- 切入点(pointcut): 对连接点拦截内容的一种定义,一般可以理解为多个连接点的结合
- 通知(Advice): 在切面的某个特定连接点上执行的动作(扩展功能),例如around,before,after等
第一步:new 一个DefaultAdvisorAutoProxyCreator,通过spring 的CGLIB代理方式来生成代理对象
@Bean
public DefaultAdvisorAutoProxyCreator
newDefaultAdvisorAutoProxyCreator() {
return new DefaultAdvisorAutoProxyCreator();
}
复习一下:
在使用任何PointCut之前,我们必须先生成一个通知(Advisor),更准确地说是一个PointcutAdvisor
DefaultPointcutAdvisor是用来结合一个PointCut和一个Advice的简单PointcutAdvisor
所谓静态切入点,就是说spring会针对目标上的每一个方法调用一次MethodMatcher的mathces方法,其返回值被缓冲器来以便日后使用,这样,对每一个方法的适用性测试只会进行一次,相对动态的效率比较高,推荐使用
第二步:以StaticMethodMatcherPointcutAdvisor的方式,重写matches方法,将注解所修饰的方法加入到业务中(这里用的是注解(@RequiredLog)方式的AOP,业务就不写了,扩展的功能就做个演示,做个输出)
@Component
public class LogMethodMatcher extends StaticMethodMatcherPointcutAdvisor{
private static final long serialVersionUID = -3857551454499822242L;
public LogMethodMatcher() {
setAdvice(new LogAdvice());
}
/ *
* Pointcut
* 方法返回值为true时,则可以为目标方法对象创建代理对象
*/
@Override
public boolean matches(Method method, Class<?> targetClass) {
try {
Method targetMethod = targetClass.getMethod(method.getName(),
method.getParameterTypes());
return targetMethod.isAnnotationPresent(RequiredLog.class);
} catch (Exception e) {
//e.printStackTrace();
return false;
}
}
}
第三步:配置拦截器
/*Advice对象:用于为目标方法添加日志操作/
public class LogAdvice implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation invocation)
throws Throwable {
System.out.println("start:"+System.currentTimeMillis());
Object result = invocation.proceed();
System.out.println("end:"+System.currentTimeMillis());
return result;
}
}
本文详细介绍了面向切面编程(AOP)的基本概念,包括切面、连接点、切入点及通知等,并通过Spring框架实现了基于注解的AOP应用示例。
3279

被折叠的 条评论
为什么被折叠?



