1、编写拦截规则的注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
String name();
}
2、编写使用注解的被拦截类
@Service
public class DemoAnnotationService {
@Action(name = "注解式拦截的add操作")
public void add(){}
}
3、编写使用方法规则的被拦截类
@Service
public class DemoMethodService {
public void add(){}
}
4、编写切面
@Aspect
@Component
public class LogAspect {
@Pointcut("@annotation(com.aop.Action)")
public void annotationPointCut() {}
@After("annotationPointCut()")
public void after(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Action action = method.getAnnotation(Action.class);
System.out.println("注解式拦截:" + action.name());
}
@Before("execution(* com.aop.DemoMethodService.*(..))")
public void before(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("方法规则拦截:" + method.getName());
}
}
5、配置类
@Configuration
@ComponentScan("com.aop")
@EnableAspectJAutoProxy //开启Spring对AspectJ的支持
public class AspectJConfig {
}
6、测试
public class Main {
public static void main(String[] args){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AspectJConfig.class);
// 注解式
DemoAnnotationService annotationService = context.getBean(DemoAnnotationService.class);
annotationService.add();
// 方法规则式
DemoMethodService methodService = context.getBean(DemoMethodService.class);
methodService.add();
}
}
测试结果