1. 定义多个切面
AOP的单个切面定义更详细:SpringBoot学习2.0-SpringAOP简单例子
定义servic
public interface AspectOrderService {
public void printOrderTest();
}
@Service
public class AspectOrderServiceImpl implements AspectOrderService {
@Override
public void printOrderTest() {
System.out.println("多切面测试...");
}
}
切面之一:
@Component
@Aspect
@Order(1)
public class AspectOrder1 {
// 定义切点
@Pointcut("execution(* com.zyf.springAOP.service.AspectOrderServiceImpl.printOrderTest(..))")
public void pointCut() {
}
@Before("pointCut()")
public void befor() {
System.out.println("AspectOrder1...befor...");
}
@After("pointCut()")
public void after() {
System.out.println("AspectOrder1...after...");
}
@AfterReturning("pointCut()")
public void afterReturning() {
System.out.println("AspectOrder1...afterReturning...");
}
}
切面之二:
@Component
@Aspect
@Order(2)
public class AspectOrder2 {
// 定义切点
@Pointcut("execution(* com.zyf.springAOP.service.AspectOrderServiceImpl.printOrderTest(..))")
public void pointCut() {
}
@Before("pointCut()")
public void befor() {
System.out.println("AspectOrder2...befor...");
}
@After("pointCut()")
public void after() {
System.out.println("AspectOrder2...after...");
}
@AfterReturning("pointCut()")
public void afterReturning() {
System.out.println("AspectOrder2...afterReturning...");
}
}
切面之三:
@Component
@Aspect
@Order(3)
public class AspectOrder3 {
// 定义切点
@Pointcut("execution(* com.zyf.springAOP.service.AspectOrderServiceImpl.printOrderTest(..))")
public void pointCut() {
}
@Before("pointCut()")
public void befor() {
System.out.println("AspectOrder3...befor...");
}
@After("pointCut()")
public void after() {
System.out.println("AspectOrder3...after...");
}
@AfterReturning("pointCut()")
public void afterReturning() {
System.out.println("AspectOrder3...afterReturning...");
}
}
junit测试:
@Autowired
private AspectOrderService aspectOrderService;
@Test
public void aspectOrderTest() {
aspectOrderService.printOrderTest();
}
输出:
AspectOrder1...befor...
AspectOrder2...befor...
AspectOrder3...befor...
多切面测试...
AspectOrder3...after...
AspectOrder3...afterReturning...
AspectOrder2...after...
AspectOrder2...afterReturning...
AspectOrder1...after...
AspectOrder1...afterReturning...
- 给连接点增加了三个切面。
- 每个切面用@Order注解添加了顺序,不然会无序执行。
- 从执行结果来看,@Before会按照@Order从小到大执行,@After和@AfterThrowing会按照@Order从大到小执行,“责任链模式”的顺序。
- 另外也可以通过实现接口Order来排序,但是@Order的方式更简单,推荐。