Spring AOP笔记
spring的面向切面编程(AOP), 这里记录下注解实现。
一、首先要声明切面Aspect,在类上加 @Aspect 注解,再加@Component 注解交给spring容器管理。
@Component
@Aspect
public class MyAspect {}
二、 定义切入点Pointcut, 方式如下:
@Pointcut("execution(* findAll(..))")
private void findAll(){}
@Pointcut("@annotation(com.company.project.annotation.AdminCheck)")
private void adminCheck(){}
@Pointcut("findAll() && adminCheck()")
private void check(){}
三、定义处理逻辑
@Before("findAll()")
public void addPrint(){
System.out.println("before findall");
}
@Before("adminCheck()")
public void admin(JoinPoint joinPoint) {
System.out.println("123");
}
@After("check1()")
public void admin3(JoinPoint joinPoint) {
System.out.println("after ...");
}
以上三步实现了最简单的Spring aop。
四、pointcut 类型
- execution 匹配方法,对方法进行织入, 这个是常用的方式。
1. execution(public * *(..)) //匹配所有 public 方法:
2. execution(* set*(..)) // 匹配所有名称以 set开始的方法
3. execution(* com.xyz.service.AccountService.*(..)) //匹配AccountService接口的所有方法
4. execution(* com.xyz.service.*.*(..)) // 匹配定义在service 包下所有类的所有方法
5. execution(* com.xyz.service..*.*(..)) // 匹配定义在service 包下 或子包下 所有类的所有方法
6. within(com.xyz.service.*) // 匹配service包下所有方法
7. within(com.xyz.service..*) // 匹配service包及其子包下所有方法
8. this(com.xyz.service.AccountService) //匹配实现AccountService接口的方法
9. target(com.xyz.service.AccountService) //目标对象实现实现AccountService接口的方法
10. args(java.io.Serializable) // 匹配单个参数且参数实现序列化的方法
11. @target(org.springframework.transaction.annotation.Transactional) //匹配 有Transaction注解的类的方法
12. @within(org.springframework.transaction.annotation.Transactional) //匹配有Transaction注解的方法
13. @args(com.xyz.security.Classified) //匹配Classified注解类有单个参数的方法
14. bean(tradeService) // 匹配名字为tradeService 的bean的方法
15. bean(*Service) //匹配名字 以Service结尾的bean的方法