AspectJ 是通過注解來描述切點與增強的。
1 開發環境要求
因為要使用注解,所以請確保使用的 Java5.0 及以上版本。
引入 AspectJ 相關類庫:
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version></dependency><dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version></dependency><dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>${aspectj.version}</version></dependency><dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>${aopalliance.version}</version></dependency>
2 編程方式
@Aspect//標識切面
public class PreRentAspect { /** * 增強邏輯 */ @Before("execution(* rent(..))")//定義切點與增強類型 public void beforeRent() { System.out.println("開始執行租賃動作"); }}
這個切面只是一個普通的 POJO,只不過加了 @Aspect 注解。
@Before("execution(* rent(..))")
中的 @Before
表示增強類型是前置增強,它的內容是 @AspectJ 切點表達式,這里表示的是在目標類的 rent() 方法上織入增強, rent() 可以包含任意入參和任意的返回值。
帶 @Aspect
的類,通過注解與代碼,將切點、增強類型和增強的橫切邏輯整合到了一起,是不是很方便呀O(∩_∩)O哈哈~
單元測試:
AspectJProxyFactory factory = new AspectJProxyFactory();//設置目標類factory.setTarget(new User());//添加切面類factory.addAspect(PreRentAspect.class);User proxy = factory.getProxy();String userId = "001";proxy.rent(userId);proxy.back(userId);
輸出結果:
--開始執行租賃動作--
User:租賃【充電寶】
User:歸還【充電寶】
3 配置方式
<!-- 目標類--><bean id="user" class="net.deniro.spring4.aspectj.User"/><!-- 切面類--><bean class="net.deniro.spring4.aspectj.PreRentAspect"/><!-- 自動創建代理--><bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
單元測試:
ApplicationContext context = new ClassPathXmlApplicationContext(spring.xml");User user = (User) context.getBean("user");String userId = "001";user.rent(userId);user.back(userId);
輸出結果與編程方式完全相同。
也可以基于 Schema 的 aop 命名空間進行配置:
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!--aspectj 驅動器 --> <aop:aspectj-autoproxy/> <!-- 目標類--> <bean id="user" class="net.deniro.spring4.aspectj.User"/> <!-- 切面類--> <bean class="net.deniro.spring4.aspectj.PreRentAspect"/></beans>
這樣的配置更加簡潔。其實在 <aop:aspectj-atuoproxy/>
內部已經采用了自動代理模式啦 O(∩_∩)O哈哈~
<aop:aspectj-atuoproxy/>
的 proxy-target-class
屬性,默認為 false ,表示使用 JDK 動態代理技術織入增強;此值為 true 則表示使用 CGLib 動態代理技術織入增強 。 如果目標類沒有聲明接口,那么即使 proxy-target-class
設置為 false,也會自動使用 CGLib 動態代理織入增強的喲O(∩_∩)O哈哈~
基于 Java5.0+ 的項目,建議使用 AspectJ 來配置切點與增強,因為這樣更簡潔、也更直接。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選