1. 程式人生 > >spring aop 001 : 增強順序

spring aop 001 : 增強順序

package com.thereisnospon.spring.demo.course.imp.c004_aop;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import
org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; /** * 如果增強在同一個切面類中宣告,則依照增強在切面類中定義的順序進行織入; * * 如果增強位於不同的切面類中,且這些切面類都實現了org.springframework.core.Ordered介面,則由介面方法的順序號決定(順序號小的先織入); * * 如果增強位於不同的切面類中,且這些切面類沒有實現org.springframework.core.Ordered介面,織入的順序是不確定的。 */
public class T002_Aop02_TargetThis2 { public static class BookService { public void doService() { System.out.println("doService"); } } @Aspect @Order(value = 2) public static class BookAspect { @Before("within(com.thereisnospon.spring.demo.course.imp.c004_aop.T002_Aop02_TargetThis2.BookService)"
) public void be() { System.out.println("BookAspect"); } } @Aspect public static class BookAspect2 implements Ordered { @Before("within(com.thereisnospon.spring.demo.course.imp.c004_aop.T002_Aop02_TargetThis2.BookService)") public void be() { System.out.println("BookAspect2"); } @Override public int getOrder() { return 1; } } @Configuration @EnableAspectJAutoProxy(proxyTargetClass = true) public static class Config { @Bean public BookAspect bookAspect() { return new BookAspect(); } @Bean public BookAspect2 bookAspect2() { return new BookAspect2(); } @Bean public BookService bookService() { return new BookService(); } } public static void test1() { ApplicationContext context = new AnnotationConfigApplicationContext(Config.class); BookService bookService = (BookService) context.getBean("bookService"); bookService.doService(); } public static void main(String[] args) { test1(); /*輸出 BookAspect2 BookAspect doService */ } }