【SSM开发框架】Spring之SpringAOP

笔记输出来源:拉勾教育Java就业急训营
如有侵权,私信立删

修改时间:2020年2月22日
作者:pp_x
邮箱:[email protected]

Proxy实现转账案例

  • 们可以将业务代码和事务代码进行拆分,通过动态代理的方式,对业务方法进行事务的增强。

常用的动态代理技术

  • JDK 代理 : 基于接口的动态代理技术,利用拦截器(必须实现invocationHandler)加上反射机制生成一个代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理,从而实现方法增强
  • CGLIB代理基于父类的动态代理技术,动态生成一个要代理的子类,子类重写要代理的类的所有不是final的方法。在子类中采用方法拦截技术拦截所有的父类方法的调用,顺势织入横切逻辑,对方法进行增强
    在这里插入图片描述

JDK动态代理

  • Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces,InvocationHandler h)
  • ClassLoader loader:类加载器 借助被代理对象获取到的类加载器
  • Class<?>[] interfaces:被代理类所需要实现的全部接口
  • InvocationHandler h :当代理对象调用接口中的任意方法 那么都会执行InvocationHandler中的invoke

代码实现

  • dao层实现类
@Repository("accountDao") //生成该类实例存入IOC容器中
public class AccountDaoImpl implements AccountDao {
    
    

    @Autowired
    private QueryRunner queryRunner;
    @Autowired
    private ConnectionUtils connectionUtils;
    @Override
    public void out(String outUser, Double money) {
    
    
        String sql = "update account set money = money - ? where name = ?";
        try {
    
    
            queryRunner.update(connectionUtils.getThreadConnection(),sql,money,outUser);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    @Override
    public void in(String inUser, Double money) {
    
    
        String sql = "update account set money = money + ? where name = ?";
        try {
    
    
            queryRunner.update(connectionUtils.getThreadConnection(),sql,money,inUser);

        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }
}
  • service层实现类
public class AccountServiceImpl implements AccountService {
    
    

    @Autowired
    private AccountDao accountDao;

    /**
     * 转账方法
     * @param outUser
     * @param inUser
     * @param money
     */
    @Override
    public void transfer(String outUser, String inUser, Double money) {
    
    


        accountDao.out(outUser,money);
        //int i = 2/0;
        accountDao.in(inUser,money);


    }
}
  • 连接工具类:保证一个线程一个连接
/**
 * 连接工具类  从数据源中获取连接 并且将获取到的连接与线程进行绑定
 * ThreadLocal:线程内部的存储类 可以在指定的线程内存储数据  key:threadlocal(当前线程) value:任意类型的值 Connection
 */
@Component//不属于三层架构以外的类使用的注解  实例化ConnectionUtils对象到容器中
public class ConnectionUtils {
    
    
    @Autowired//从容器中获取一个DataSource类型的对象
    private DataSource dataSource;

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    /**
     * 获取当前线程绑定的连接 如果获取到的连接为空则从数据源中获取链接并且放入ThreadLocal中(绑定当前线程)
     *
     */
    public Connection getThreadConnection(){
    
    
        //1、从ThreadLocal中获取连接
        Connection connection = threadLocal.get();
        //2、判断当前线程是否为空
        if (connection == null){
    
    
            //从数据源中获取connection 并存入ThreadLocal
            try {
    
    
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
        return connection;
    }

    /**
     * 解除绑定
     */
    public void removeThreadConnection(){
    
    
        threadLocal.remove();
    }
}
  • 事务管理工具类
/**
 * 事务管理器工具类:包含 开启事务 提交事务 回滚事务 释放资源
 * 必须保证是同一个Connection
 */
@Component
public class TransactionManager {
    
    
    @Autowired
    private ConnectionUtils connectionUtils;
    /**
     * 开启事务
     */
    public void beginTransaction(){
    
    
        //获取connection对象
        Connection connection = connectionUtils.getThreadConnection();

        try {
    
    
            connection.setAutoCommit(false);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
    
    
        //获取到的是同一个connection
        Connection connection  = connectionUtils.getThreadConnection();

        try {
    
    
            connection.commit();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback(){
    
    
        //获取到的是同一个connection
        Connection connection  = connectionUtils.getThreadConnection();
        try {
    
    
            connection.rollback();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     */
    public void release(){
    
    

        Connection connection = connectionUtils.getThreadConnection();

        try {
    
    
            //将手动提交事务改成自动提交事务
            connection.setAutoCommit(true);
            //将连接归还连接池
            connectionUtils.getThreadConnection().close();
            //接触线程绑定
            connectionUtils.removeThreadConnection();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }

    }
}
  • jdk工厂类
/*
    jdk动态代理工厂类
 */
@Component
public class JDkProxyFactory {
    
    
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionManager transactionManager;
    /*
        采用动态代理技术来生成目标类的对象
        ClassLoader loader,  类加载器  借助被代理对象获取到的类加载器

        Class<?>[] interfaces, 被代理类所需要实现的全部接口
          InvocationHandler h  当代理对象调用接口中的任意方法 那么都会执行InvocationHandler中的invoke
     */
    public AccountService createAccountServiceJDKProxy(){
    
    
        //生成代理对象
        AccountService accountServiceProxy  = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
    
    
            @Override
            //proxy : 当前代理对象的引用  method: 被调用的目标方法的引用  args:被调用的目标方法所用到的参数
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
                try {
    
    

                    if (method.getName().equals("transfer")){
    
    
                        //手动开启事务
                        //第一次获取Connection对象
                        transactionManager.beginTransaction();
                        System.out.println("进行了前置增强");
                        //被代理对象的原方法执行
                        //当调用的方法文transfer时 method就为transfer
                        method.invoke(accountService, args);
                        //手动提交事务
                        System.out.println("进行了后置增强");
                        transactionManager.commit();
                    }else {
    
    
                        method.invoke(accountService,args);
                    }

                } catch (Exception e) {
    
    
                    e.printStackTrace();
                    //手动回滚事务
                    transactionManager.rollback();
                }finally {
    
    
                    //手动释放资源
                    transactionManager.release();
                }
                return null;
            }
        });
        return accountServiceProxy;
    }
}
  • 测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
    
    "classpath:applicationContext.xml"})
public class AccountServiceTest {
    
    
    @Autowired
    private AccountService accountService;
    @Autowired
    private JDkProxyFactory jDkProxyFactory;
    @Autowired
    private CglibProxyFactory cglibProxyFactory;

    /*
    测试JDK动态代理
     */
    @Test
    public void testTransferProxyJDK(){
    
    
        //当前返回的是AccountService的代理对象
        AccountService accountServiceJDKProxy = jDkProxyFactory.createAccountServiceJDKProxy();
        //代理接口调用接口中的任何方法时  都会调用底层的invoke方法
        accountServiceJDKProxy.transfer("tom","jerry",100d);
    }
}

Cglib动态代理

  • Enhancer.create(x,y)
  • 参数一:目标类的字节码对象
  • 参数二: 动作类 当代理对象调用目标对象中的原方法时会执行intercept方法

代码实现

  • 其他工具类实现类代码省略
  • cglib工厂类
/*
    该类采用Cglib动态代理来对目标类Account ServiceImpl进行动态增强(添加事务控制)
 */
@Component
public class CglibProxyFactory {
    
    
    @Autowired
    private AccountService accountService;
    @Autowired
    private TransactionManager transactionManager;

    public AccountService createAccountServiceCglibProxy(){
    
    
        // 编写cglib对应的API来生产代理对象进行返回
        // Enhancer:cglib的字节码增强器
        // 参数一:目标类的字节码对象  参数二: 动作类 当代理对象调用目标对象中原方法时 会执行intercept方法
        AccountService accountServiceProxy = (AccountService) Enhancer.create(accountService.getClass(), new MethodInterceptor() {
    
    
            // o:代表生成的代理对象引用  method:调用目标方法的引用  objects:方法入参 methodProxy:代理方法
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    
    
                try {
    
    
                    //手动开启事务
                    //第一次获取Connection对象
                    transactionManager.beginTransaction();

                    //被代理对象的原方法执行
                    //当调用的方法文transfer时 method就为transfer
                    method.invoke(accountService, objects);
                    //手动提交事务
                    transactionManager.commit();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                    //手动回滚事务
                    transactionManager.rollback();
                } finally {
    
    
                    //手动释放资源
                    transactionManager.release();
                }
                return null;
            }
        });
        return accountServiceProxy;
    }
}
  • 测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
    
    "classpath:applicationContext.xml"})
public class AccountServiceTest {
    
    
    @Autowired
    private AccountService accountService;
    @Autowired
    private JDkProxyFactory jDkProxyFactory;
    @Autowired
    private CglibProxyFactory cglibProxyFactory;
    @Test
    public void testTransferProxyCglib(){
    
    
        AccountService accountServiceCglibProxy = cglibProxyFactory.createAccountServiceCglibProxy();
        accountServiceCglibProxy.transfer("tom","jerry",100d);
    }
}

SpringAOP

  • AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程
  • AOP 是 OOP(面向对象编程) 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率
  • 好处:
    • 在程序运行期间,在不修改源码的情况下对方法进行功能增强
    • 逻辑清晰,开发核心业务的时候,不必关注增强业务的代码
    • 减少重复代码,提高开发效率,便于后期维护

AOP底层实现

  • 实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。

AOP相关术语

  • Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
  • Target(目标对象):代理的目标对象
  • Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
  • Joinpoint(连接点):所谓连接点是指那些可以被拦截到的点。在spring中,这些点指的是方法,因为 spring只支持方法类型的连接点
  • Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义
  • Advice(通知/ 增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知 分类:前置通知、后置通知、异常通知、最终通知、环绕通知
  • Aspect(切面):是切入点和通知(引介)的结合
  • Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织 入,而AspectJ采用编译期织入和类装载期织入

AOP开发明确事项

  • 开发阶段(程序员需要做的)
    • 编写核心业务代码(目标类的目标方法) 切入点
    • 把公用代码抽取出来,制作成通知(增强功能方法) 通知
    • 在配置文件中,声明切入点与通知间的关系,即切面
  • 运行阶段(Spring框架完成的)
    • Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
  • 底层代理实现
    • 在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
    • 当bean实现接口时,会用JDK代理模式
    • 当bean没有实现接口,用cglib实现
    • 可以强制使用cglib(在spring配置中加入<aop:aspectjautoproxy proxyt-target-class=”true”/>

基于xml的AOP开发

  • 需要导入的坐标
<dependencies>
        <!--导入spring的context坐标,context依赖aop-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <!-- aspectj的织入(切点表达式需要用到该jar包) -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <!--spring整合junit-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
  • 目标接口实现类
public interface AccountService {
    
    
    public void transfer();
}

public class AccountServiceImpl implements AccountService {
    
    
    public void transfer() {
    
    
        System.out.println("转账方法 执行了");
//        int i = 1/0;
    }
}
  • 通知类
public class MyAdvice {
    
    
    public void before(){
    
    
        System.out.println("前置通知执行了");
    }
    public void afterReturn(){
    
    
        System.out.println("后置通知执行了");
    }
    public void afterThrowing(){
    
    
        System.out.println("异常通知执行了");

    }
    public void after(){
    
    
        System.out.println("最终通知执行了");
    }
    //ProceedingJoinPoint正在执行的连接点:切点
    public void around(ProceedingJoinPoint proceedingJoinPoint){
    
    
        Object proceed= null;
        try {
    
    
            System.out.println("前置通知执行了");
            proceed = proceedingJoinPoint.proceed();
            System.out.println("后置通知执行了");
        } catch (Throwable throwable) {
    
    

            throwable.printStackTrace();
            System.out.println("异常通知执行了");
        }finally {
    
    
            System.out.println("最终通知执行了");
        }
    }
}
  • 配置文件配置
<!--  目标类交给ioc容器  -->
    <bean id="accountService" class="com.lagou.service.impl.AccountServiceImpl"></bean>
<!--  通知类交给ioc容器  -->
    <bean id="myAdvice" class="com.lagou.advice.MyAdvice"></bean>

<!--  aop 配置  -->
    <aop:config>
        <!--   抽取切点表达式      -->
        <aop:pointcut id="myPointCut" expression="execution(public void com.lagou.service.impl.AccountServiceImpl.transfer())"/>
        <!-- 配置切面:切入点和通知       -->
        <aop:aspect ref="myAdvice">
            <aop:before method="before" pointcut-ref="myPointCut"/>
          <aop:after-returning method="afterReturn" pointcut-ref="myPointCut"/>
            <aop:after-throwing method="afterThrowing" pointcut-ref="myPointCut"/>
          <aop:after method="after" pointcut-ref="myPointCut"/>
            <aop:around method="around" pointcut-ref="myPointCut"/>
        </aop:aspect>
    </aop:config>
  • 测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
    
    "classpath:applicationContext.xml"})
public class AccountServiceTest {
    
    
    @Autowired
    private AccountService accountService;

    @Test
    public void test(){
    
    
        accountService.transfer();
    }
}

XML配置AOP详解

切点表达式

  • execution([修饰符] 返回值类型 包名.类名.方法名(参数))
 execution([修饰符] 返回值类型 包名.类名.方法名(参数))
        execution(public void com.lagou.servlet.impl.AccountServiceImpl.transfer(java.lang.String))

        - 访问修饰符可以省略
        execution(void com.lagou.servlet.impl.AccountServiceImpl.transfer(java.lang.String))

        - 返回值类型、包名、类名、方法名可以使用星号 * 代替,代表任意
        execution(* *.*.*.*.*.*())

        - 包名与类名之间一个点 . 代表当前包下的类,两个点 .. 表示当前包及其子包下的类
        execution(* *..*.*())

        - 参数列表可以使用两个点 .. 表示任意个数,任意类型的参数列表
        execution(* *..*.*(..))

切点表达式抽取

<aop:pointcut id="myPointcut" expression="execution(* com.lagou.service..*.* (..))">
</aop:pointcut>

通知类型

  • 配置语法
    <aop:通知类型 method=“通知类中方法名” pointcut=“切点表达式"></aop:通知类型>
通知类型 说明
前置通知 <aop:before> 用于配置前置通知。指定增强的方法在切入点方法之前执行
后置通知<aop:afterReturning> 用于配置后置通知。指定增强的方法在切入点方法之后执行
异常通知<aop:afterThrowing> 用于配置异常通知。指定增强的方法出现异常后执行
最终通知<aop:after> 无论切入点方法执行时是否有异常,都会执行
环绕通知<aop:around> 开发者可以手动控制增强代码在什么时候执行
  • 其中环绕通知独立使用

基于注解的AOP开发

  • 导入的坐标同上
  • 目标类
@Service
public class AccountServiceImpl implements AccountService{
    
    
    public void transfer() {
    
    
        System.out.println("转账方法 执行了");
//        int i = 1/0;
    }
}
  • 通知类
@Component
//将此类升级为切面类  配置切入点和通知的关系
@Aspect
public class MyAdvice {
    
    

    //抽取切点表达式
    @Pointcut("execution(* com.lagou.service.impl.AccountServiceImpl.*(..))")
    public void myPoint(){
    
    

    }
    @Before("MyAdvice.myPoint()")
    public void before(){
    
    
        System.out.println("前置通知执行了");
    }
    @AfterReturning("MyAdvice.myPoint()")
    public void afterReturn(){
    
    
        System.out.println("后置通知执行了");
    }
    @AfterThrowing("MyAdvice.myPoint()")
    public void afterThrowing(){
    
    
        System.out.println("异常通知执行了");

    }
    @After("MyAdvice.myPoint()")
    public void after(){
    
    
        System.out.println("最终通知执行了");
    }
    //ProceedingJoinPoint正在执行的连接点:切点
    public void around(ProceedingJoinPoint proceedingJoinPoint){
    
    
        Object proceed= null;
        try {
    
    
            System.out.println("前置通知执行了");
            proceed = proceedingJoinPoint.proceed();
            System.out.println("后置通知执行了");
        } catch (Throwable throwable) {
    
    

            throwable.printStackTrace();
            System.out.println("异常通知执行了");
        }finally {
    
    
            System.out.println("最终通知执行了");
        }



    }
}
  • 测试同上

注解配置AOP详解

切点表达式抽取

@Pointcut("execution(* com.lagou..*.*(..))")
public void myPoint(){
    
    } 
@Before("MyAdvice.myPoint()") 
public void before() {
    
     
	System.out.println("前置通知..."); 
}

通知类型

通知类型 说明
前置通知 @Before 用于配置前置通知。指定增强的方法在切入点方法之前执行
后置通知@AfterReturning 用于配置后置通知。指定增强的方法在切入点方法之后执行
异常通知@AfterThrowing 用于配置异常通知。指定增强的方法出现异常后执行
最终通知@After 无论切入点方法执行时是否有异常,都会执行
环绕通知@Around 开发者可以手动控制增强代码在什么时候执行
  • 注意:当前四个通知组合在一起时,执行顺序如下:
    • @Before -> @After -> @AfterReturning(如果有异常:@AfterThrowing)

纯注解配置

//使此类成为核心配置类
@Configuration
//开启注解扫描
@ComponentScan("com.lagou")
//开启aop自动代理
@EnableAspectJAutoProxy
public class SpringConfig {
    
    

}
  • 其中@EnableAspectJAutoProxy代替 <aop:aspectj-autoproxy />标签

AOPxml优化转账案例

  • 通知类(事务管理器)
/**
 * 事务管理器工具类:包含 开启事务 提交事务 回滚事务 释放资源
 * 必须保证是同一个Connection
 */
@Component("transactionManager")
public class TransactionManager {
    
    
    @Autowired
    private ConnectionUtils connectionUtils;
    /**
     * 开启事务
     */
    public void beginTransaction(){
    
    
        //获取connection对象
        Connection connection = connectionUtils.getThreadConnection();

        try {
    
    
            connection.setAutoCommit(false);
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
    
    
        //获取到的是同一个connection
        Connection connection  = connectionUtils.getThreadConnection();

        try {
    
    
            connection.commit();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback(){
    
    
        //获取到的是同一个connection
        Connection connection  = connectionUtils.getThreadConnection();
        try {
    
    
            connection.rollback();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     */
    public void release(){
    
    

        Connection connection = connectionUtils.getThreadConnection();

        try {
    
    
            //将手动提交事务改成自动提交事务
            connection.setAutoCommit(true);
            //将连接归还连接池
            connectionUtils.getThreadConnection().close();
            //接触线程绑定
            connectionUtils.removeThreadConnection();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }

    }
}

  • xml配置
<?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:context="http://www.springframework.org/schema/context"
       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/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--  开启注解扫描  -->
    <context:component-scan base-package="com.lagou"></context:component-scan>
<!--  引入properties  -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- 配置DATa Source-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
<!--  配置queryRunner  -->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
    <!--  AOP配置  -->
    <aop:config>
        <!-- 切点表达式   -->
        <aop:pointcut id="myPointcut" expression="execution(* com.lagou.service.impl.AccountServiceImpl.*(..))"/>
        <!--配置切面        -->
        <aop:aspect ref="transactionManager">
            <aop:before method="beginTransaction" pointcut-ref="myPointcut"/>
            <aop:after-returning method="commit" pointcut-ref="myPointcut"/>
            <aop:after-throwing method="rollback" pointcut-ref="myPointcut"/>
            <aop:after method="release" pointcut-ref="myPointcut"/>
        </aop:aspect>
    </aop:config>
</beans>

AOP注解优化转账案例

  • 配置
<?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:context="http://www.springframework.org/schema/context"
       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/context
		http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--  开启注解扫描  -->
    <context:component-scan base-package="com.lagou"></context:component-scan>
<!--  引入properties  -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- 配置DATa Source-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
<!--  配置queryRunner  -->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
</beans>    
  • 事务管理器(通知类)
@Component 
@Aspect
public class TransactionManager {
    
     
@Autowired ConnectionUtils connectionUtils; 
@Around("execution(* com.lagou.serivce..*.*(..))") 
public Object around(ProceedingJoinPoint pjp) {
    
     
	Object object = null; 
	try {
    
    
		// 开启事务 
		connectionUtils.getThreadConnection().setAutoCommit(false); 
		// 业务逻辑 
		pjp.proceed(); 
		// 提交事务 
		connectionUtils.getThreadConnection().commit(); 
	} catch (Throwable throwable) {
    
     
		throwable.printStackTrace(); 
		// 回滚事务 
		try {
    
    
			connectionUtils.getThreadConnection().rollback(); 
			} 
		catch (SQLException e) {
    
     
			e.printStackTrace(); 
			} 
		} finally {
    
     
		try {
    
    
			connectionUtils.getThreadConnection().setAutoCommit(true); 
			connectionUtils.getThreadConnection().close(); 
			connectionUtils.removeThreadConnection(); } 
		catch (SQLException e) {
    
     
			e.printStackTrace(); 
			} 
		}
		return object; 
		} 
}

猜你喜欢

转载自blog.csdn.net/weixin_46303867/article/details/113942042
今日推荐