javascript
Spring AOP的一个简单实现
針對學(xué)習(xí)筆記(六)中的購買以及退貨代碼,我們加入AOP框架,實現(xiàn)同樣一個功能。
首先配置XML:service采用和之前一樣的代碼,只是沒有通過實現(xiàn)接口來實現(xiàn),而是直接一個實現(xiàn)類。transactionManager依舊為之前的事務(wù)管理器。
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd "><!-- 業(yè)務(wù)類 --><bean id="service" class="aop_part.Demo2.GodService"></bean><!-- 切面類 --><bean id="transactionManager" class="aop_part.Demo1.TransactionManager"></bean><!-- 切入點 --><aop:config><aop:aspect id="transactionAspect" ref="transactionManager"><aop:before method="transaction_start"pointcut="execution(* aop_part.Demo2.*Service.*(..))"/><aop:after-returning method="transaction_submit"pointcut="execution(* aop_part.Demo2.*Service.*(..))"/><aop:after-throwing method="transaction_rollback"pointcut="execution(* aop_part.Demo2.*Service.*(..))"/></aop:aspect></aop:config></beans>我們通過再xml中配置aop參數(shù),實現(xiàn)了將事務(wù)操作插入到service的前中后中。
寫一個Text類,來觀察輸出的結(jié)果:
package aop_part.Demo2;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;/*** Created by Richard on 2017/7/28.*/ public class test {public static void main(String[] args) {ApplicationContext context=new ClassPathXmlApplicationContext("aop_part/Demo2/aop_Context.xml");GodService godService= (GodService) context.getBean("service");System.out.println(godService.getClass().getName());godService.buy("rekent","AOP_Study");godService.returnGod(1100);} }結(jié)果和預(yù)期一樣,與之前是一致的:
aop_part.Demo2.GodService$$EnhancerBySpringCGLIB$$3f2fc81 【事務(wù)開始】用戶rekent購買了AOP_Study 【事務(wù)提交】 【事務(wù)開始】訂單1100申請退回 【事務(wù)提交】Process finished with exit code 0與此同時,Spring 框架通過Java SE動態(tài)代理和cglib來實現(xiàn)AOP功能:
當(dāng)明確指定目標(biāo)類實現(xiàn)的業(yè)務(wù)接口時,Spring采用動態(tài)代理,也可以強制使用cglib
當(dāng)沒有指定目標(biāo)類的接口時,Spring使用cglib進行字節(jié)碼增強。
此處由于沒有申明接口,所以Spring采用cglib來實現(xiàn)AOP,我們通過反射獲取到了cglib動態(tài)生成的代理對象的類名,即aop_part.Demo2.GodService$$EnhancerBySpringCGLIB$$3f2fc81
轉(zhuǎn)載于:https://www.cnblogs.com/rekent/p/7251521.html
總結(jié)
以上是生活随笔為你收集整理的Spring AOP的一个简单实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 比较器
- 下一篇: FZU 2087 统计树边【MST相关