網上關於AOP的例子好多,各種名詞解釋也一大堆,反正名詞各種晦澀,自己寫個最最最簡單的例子入門mark一下,以后再深入學習。
maven依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
定義切面
@Aspect @Configuration public class AopConfiguration { }
切面內定義切入點,就是執行的條件
@Pointcut("execution(* com.test.service.*.*(..))") public void executeService() { }
切入點的方法不用任何代碼,返回值是void,最重要的是執行的條件的表達式:
1)execution:用於匹配子表達式。 //匹配com.cjm.model包及其子包中所有類中的所有方法,返回類型任意,方法參數任意 @Pointcut("execution(* com.cjm.model..*.*(..))") public void before(){} 2)within:用於匹配連接點所在的Java類或者包。 //匹配Person類中的所有方法 @Pointcut("within(com.cjm.model.Person)") public void before(){} //匹配com.cjm包及其子包中所有類中的所有方法 @Pointcut("within(com.cjm..*)") public void before(){} 3) this:用於向通知方法中傳入代理對象的引用。 @Before("before() && this(proxy)") public void beforeAdvide(JoinPoint point, Object proxy){ //處理邏輯 } 4)target:用於向通知方法中傳入目標對象的引用。 @Before("before() && target(target) public void beforeAdvide(JoinPoint point, Object proxy){ //處理邏輯 } 5)args:用於將參數傳入到通知方法中。 @Before("before() && args(age,username)") public void beforeAdvide(JoinPoint point, int age, String username){ //處理邏輯 } 6)@within :用於匹配在類一級使用了參數確定的注解的類,其所有方法都將被匹配。 @Pointcut("@within(com.cjm.annotation.AdviceAnnotation)") - 所有被@AdviceAnnotation標注的類都將匹配 public void before(){} 7)@target :和@within的功能類似,但必須要指定注解接口的保留策略為RUNTIME。 @Pointcut("@target(com.cjm.annotation.AdviceAnnotation)") public void before(){} 8)@args :傳入連接點的對象對應的Java類必須被@args指定的Annotation注解標注。 @Before("@args(com.cjm.annotation.AdviceAnnotation)") public void beforeAdvide(JoinPoint point){ //處理邏輯 } 9)@annotation :匹配連接點被它參數指定的Annotation注解的方法。也就是說,所有被指定注解標注的方法都將匹配。 @Pointcut("@annotation(com.cjm.annotation.AdviceAnnotation)") public void before(){} 10)bean:通過受管Bean的名字來限定連接點所在的Bean。該關鍵詞是Spring2.5新增的。 @Pointcut("bean(person)") public void before(){}
接下來定義通知,就是行為唄,常用的包括Before,Around,After等
@Before("executeService() &&"+"args(name)") public void before(String name) { System.out.println("before say hello"); System.out.println("name = "+name); } @AfterReturning("executeService()") public void after() { System.out.println("after return"); }
這樣調用com.test.service包下所有類的方法前都先回執行@Before的行為,結束都會執行@AfterReturning的行為。
更為詳細的介紹參考:http://www.cnblogs.com/lic309/p/4079194.html