簡介
上文已經提到了Spring AOP的概念以及簡單的靜態代理、動態代理簡單示例,鏈接地址:https://www.cnblogs.com/chenzhaoren/p/9959596.html
本文將介紹Spring AOP的常用注解以及注解形式實現動態代理的簡單示例。
常用注解
@aspect:定義切面
@pointcut:定義切點
@Before:前置通知,在方法執行之前執行
@After:后置通知,在方法執行之后執行?
@AfterRunning:返回通知,在方法返回結果之后執行
@AfterThrowing:異常通知,在方法拋出異常之后執行
@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 {@overridepublic 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/beanshttp://www.springframework.org/schema/beans/spring-beans-4.2.xsdhttp://www.springframework.org/schema/aophttp://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. 輸出結果
*注解環繞通知實現 - 環繞前*
*注解前置通知實現*
我是內褲外穿的超人!!!
*注解環繞通知實現 - 環繞后*
*注解后置通知實現*
?