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/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

转载于:https://www.cnblogs.com/rekent/p/7251521.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值