Spring AOP的一个简单实现

时间:2022-06-09
本文章向大家介绍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