原文: https://howtodoinjava.com/spring-aop/spring-aop-specifying-aspects-ordering/
在上一个教程中,我们了解了 spring aop 关键术语和示例 。 这些我们创建了一个日志记录切面,然后应用于UserManager类。 假设您的应用程序中有多个切面,并且可以将它们应用于某种方法。 如果将多个切面应用到同一个连接点,除非您使用@Order注解或org.springframework.core.Ordered接口明确指定了切面,否则将不会确定这些切面的优先级/顺序。 在这个例子中,我们将看到一个有序切面的例子。
指定切面顺序
如前所述,要指定切面的顺序,您有两种方法:
1)使用@Order注解指定切面的排序
这很简单。 使用如下注解。
@Aspect@Order(0)public class EmployeeCRUDTransactionAspect{@Before("execution(* EmployeeManager.getEmployeeById(..))")public void getEmployeeById(JoinPoint joinPoint){System.out.println("EmployeeCRUDTransactionAspect.getEmployeeById() : " + joinPoint.getSignature().getName());}}@Aspect@Order(1)public class EmployeeCRUDLoggingAspect{@Before("execution(* EmployeeManager.getEmployeeById(..))")public void logBefore(JoinPoint joinPoint){System.out.println("EmployeeCRUDAspect.logBefore() : " + joinPoint.getSignature().getName());}}
2)通过实现org.springframework.core.Ordered接口指定切面排序
这太容易了。
@Aspectpublic class EmployeeCRUDLoggingAspect implements Ordered{//Override this methodpublic int getOrder() {return 0;}@Before("execution(* EmployeeManager.getEmployeeById(..))")public void logBefore(JoinPoint joinPoint){System.out.println("EmployeeCRUDAspect.logBefore() : " + joinPoint.getSignature().getName());}}@Aspectpublic class EmployeeCRUDTransactionAspect implements Ordered{//Override this methodpublic int getOrder() {return 1;}@Before("execution(* EmployeeManager.getEmployeeById(..))")public void getEmployeeById(JoinPoint joinPoint){System.out.println("EmployeeCRUDTransactionAspect.getEmployeeById() : " + joinPoint.getSignature().getName());}}
现在该测试顺序是否有效。 在applicationContext.xml文件中配置两个切面。
<aop:aspectj-autoproxy /><context:component-scan base-package="com.howtodoinjava.demo.aop" /><bean id="transactionAspect" class="com.howtodoinjava.demo.aop.EmployeeCRUDTransactionAspect" /><bean id="loggingAspect" class="com.howtodoinjava.demo.aop.EmployeeCRUDLoggingAspect" />
让我们运行以下示例:
public class TestAOP{@SuppressWarnings("resource")public static void main(String[] args){ApplicationContext context = new ClassPathXmlApplicationContext("com/howtodoinjava/demo/aop/applicationContext.xml");EmployeeManager manager = context.getBean(EmployeeManager.class);manager.getEmployeeById(1);}}Output:EmployeeCRUDAspect.logBefore() : getEmployeeByIdEmployeeCRUDTransactionAspect.getEmployeeById() : getEmployeeByIdMethod getEmployeeById() called
很棒。 Spring AOP 切面的顺序正在按预期工作。
祝您学习愉快!
