aop-面向切面编程
aop-面向切面编程
1、业务逻辑
com.example.aop.DemoMethodService 是业务逻辑类,需要在其方法上织入额外代码,这个类不需要任何改动,完全解耦
2、切面
LogAspect 是切面,定义切点和织入代码
在类上添加 @Aspect 注解
1、基于方法规则式拦截
//在方法上添加对应注解,指定返回类型,方法签名,即可直接织入到对应的方法
//执行目标方法时,在指定的时机自动执行这个方法
@Before("execution(* com.example.aop.DemoMethodService.*(..))")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("方法规则式拦截," + method.getName());
}
2、注解式拦截
//此规则适用于目标方法上有注解的情况
//1、编写切点,指定目标方法上的注解
@Pointcut("@annotation(com.example.aop.Action2)")
public void annotationPointCut2(){
}
//2、编写Advice,规定此Advice适用的切点
@After("annotationPointCut()")
public void afterAdd(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
Action action = method.getAnnotation(Action.class);
System.out.println("after*******************注解式拦截: " + action.name());
}
//注解了com.example.aop.Action2 的方法执行时,将自动在指定的时机执行织入的代码

浙公网安备 33010602011771号