簡介html
上文已經提到了Spring AOP的概念以及簡單的靜態代理、動態代理簡單示例,連接地址:https://www.cnblogs.com/chenzhaoren/p/9959596.htmlspring
本文將介紹Spring AOP的經常使用註解以及註解形式實現動態代理的簡單示例。ide
經常使用註解測試
@aspect:定義切面spa
@pointcut:定義切點代理
@Before:前置通知,在方法執行以前執行code
@After:後置通知,在方法執行以後執行 component
@AfterRunning:返回通知,在方法返回結果以後執行xml
@AfterThrowing:異常通知,在方法拋出異常以後執行htm
@Around:環繞通知,圍繞着方法執行
啓動Spring AOP註解自動代理
1. 在 classpath 下包含 AspectJ 類庫:aopalliance.jar、aspectj.weaver.jar 和 spring-aspects.jar
2. 將 aop Schema 添加到 Bean 配置文件 <beans> 根元素中。
3. 在 Bean 配置文件中定義一個空的 XML 元素 <aop:aspectj-autoproxy proxy-target-class="true"/>
(當 Spring IOC 容器檢測到 Bean配置文件中的<aop:aspectj-autoproxy proxy-target-class="true"/> 元素時,會自動爲與 AspectJ 切面匹配的 Bean 建立代理。)
代碼示例
1. 定義被代理類接口
packege com.czr.aop.model; public interface superMan{ //自我介紹 public void introduce(); }
2. 定義被代理類
packege com.czr.aop.model;
@Component("superMan") public class SuperManImpl implements SuperMan { @override public void introduce(){ System.out.println("我是內褲外穿的超人!!!"); } }
3. 定義切點類
package com.czr.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Component("annotationAop") @Aspect public class AnnotationAop { //定義切點 @Pointcut("execution(* com.czr.aop.model.*(..))") public void pointCutName(){} @Before("pointCutName()") public void beforeAdvice(){ System.out.println("*註解前置通知實現*"); } //後置通知 @After("pointCutName()") public void afterAdvice(){ System.out.println("*註解後置通知實現*"); } //環繞通知。ProceedingJoinPoint參數必須傳入。 @Around("pointCutName()") public void aroudAdvice(ProceedingJoinPoint pjp) throws Throwable{ System.out.println("*註解環繞通知實現 - 環繞前*"); pjp.proceed();//執行方法 System.out.println("*註解環繞通知實現 - 環繞後*"); } }
4. 定義Spring文件aop.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd"> <!-- 開啓註解掃描 --> <context:component-scan base-package="com.czr.aop,com.czr.aop.model"/> <!-- 開啓aop註解方式 --> <aop:aspectj-autoproxy/> </beans>
5. 定義測試類
package com.czr.aop; public class Test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("aop.xml"); SuperMan sm= (SuperMan)ctx.getBean("superMan"); sm.introduce(); } }
6. 輸出結果
*註解環繞通知實現 - 環繞前*
*註解前置通知實現* 我是內褲外穿的超人!!! *註解環繞通知實現 - 環繞後*
*註解後置通知實現*