日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Spring AOP的一个简单实现

發布時間:2025/7/25 50 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring AOP的一个简单实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

針對學習筆記(六)中的購買以及退貨代碼,我們加入AOP框架,實現同樣一個功能。

首先配置XML:service采用和之前一樣的代碼,只是沒有通過實現接口來實現,而是直接一個實現類。transactionManager依舊為之前的事務管理器。

<?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 "><!-- 業務類 --><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參數,實現了將事務操作插入到service的前中后中。

寫一個Text類,來觀察輸出的結果:

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);} }

結果和預期一樣,與之前是一致的:

aop_part.Demo2.GodService$$EnhancerBySpringCGLIB$$3f2fc81 【事務開始】用戶rekent購買了AOP_Study 【事務提交】 【事務開始】訂單1100申請退回 【事務提交】Process finished with exit code 0

與此同時,Spring 框架通過Java SE動態代理和cglib來實現AOP功能:

  當明確指定目標類實現的業務接口時,Spring采用動態代理,也可以強制使用cglib

  當沒有指定目標類的接口時,Spring使用cglib進行字節碼增強。

  此處由于沒有申明接口,所以Spring采用cglib來實現AOP,我們通過反射獲取到了cglib動態生成的代理對象的類名,即aop_part.Demo2.GodService$$EnhancerBySpringCGLIB$$3f2fc81

轉載于:https://www.cnblogs.com/rekent/p/7251521.html

總結

以上是生活随笔為你收集整理的Spring AOP的一个简单实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。