Spring AOP的一个简单实现
2024-08-29 15:14:58
针对学习笔记(六)中的购买以及退货代码,我们加入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/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://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
最新文章
- activity切换时的overridePendingTransition动画效
- ADO.NET笔记——使用DataAdapter执行增删改操作
- JavaScript基础大全篇
- .NET 基础 一步步 一幕幕[面向对象之静态、非静态]
- js提交前弹出提示框
- CSDN Androidclient生产 导航帖
- 理解javascript中的回调函数(callback)
- apacheds的客户端
- poj 3694(割边+lca)
- web---资源的下载及中文乱码问题
- ECMA Script 6_symbol(symbol.iterator) 新接口_iterator接口
- tomcat没有编译重新编写的代码
- Leeetcode--581. Shortest Unsorted Continuous Subarray
- ES6 箭头函数下的this指向
- CTF-练习平台-Misc之 猜?
- Django中间件执行流程
- 复习及总结--.Net线程篇(3)
- 理解Underscore中的节流函数
- fwrite()
- 洛谷 P2251 质量检测