spring AOP

spring AOP
Spring的核心特性就是IOC和AOP,之前整理了SpringIOC,这篇文章就来写一下SpringAOP(Aspect Oriented Programming),即:面向切面编程

简单转账功能

AOP转账功能

引入代理模式解决事务

代码实现
事务管理器:TransactionManager.java

package transaction;

@Component
public class TransactionManager {
    // 数据库连接工具类
    @Autowired
    private ConnectionUtils connectionUtils;

    /**
     * 开启事务
     */
    public void beginTransaction() {
        try {
            System.out.println("开启事务");
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    public void commit() {
        try {
            System.out.println("提交事务");
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    public void rollback() {
        try {
            System.out.println("回滚事务");
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    public void release() {
        try {
            System.out.println("释放连接");
            connectionUtils.getThreadConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        connectionUtils.removeConnection();
    }
}

事务代理工具类:TransactionProxyUtils

package utils;

@Component
public class TransactionProxyUtils {
    //被代理的业务类接口
    @Autowired
    private AccountService accountService;
    //提供事务管理的工具类
    @Autowired
    private TransactionManager transactionManager;

    /**
     * 获取AccountService代理对象
     *
     * @return
     */
    public AccountService getAccountService() {
        return (AccountService) Proxy.newProxyInstance(
                accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    /**
                     * 添加事务的支持
                     *
                     * @param proxy     被代理的对象实例本身
                     * @param method    被代理对象正在执行的方法对象
                     * @param args      正在访问的方法参数对象
                     * @return
                     * @throws Throwable
                     */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                        //
                        Object rtValue = null;
                        try {
                            // 执行操作前开启事务
                            transactionManager.beginTransaction();
                            // 执行操作
                            rtValue = method.invoke(accountService, args);
                            // 执行操作后提交事务
                            transactionManager.commit();
                            // 返回结果
                            return rtValue;
                        } catch (Exception e) {
                            // 捕捉到异常执行回滚操作
                            transactionManager.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            // 最终释放连接
                            transactionManager.release();
                        }
                    }
                });

    }
}

核心配置文件:applicationContext.xml
1.添加事务管理bean


<context:component-scan base-package="transaction"/>

2.配置代理Service

<!--配置代理的service-->
<bean id="transactionProxyAccountService" factory-bean="transactionProxyUtils" factory-method="getAccountService"/>

3.Account模块测试类:AccountTest.java

@Qualifier("transactionProxyAccountService")

执行结果
首先将数据库中两账户余额都改为1000

update account set money = 1000;

控制台打印结果
在这里插入图片描述

引入AOP(XML)

相关概念
1.Join point(连接点)
2.Pointcut(切入点)
3.Advice(通知)
4.Target(目标)
5.Aspect(切面)
6.Weaving(织入)
7.Proxy(代理)

代码实现

1.删除事务代理工具类:TransactionProxyUtils.java
2.导入aspectjweaver包

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.3</version>
</dependency>

配置文件中添加 AOP 的相关配置

<!-- aop相关的节点配置 -->
<aop:config>
    <!-- 切入点  表示哪些类的哪些方法在执行的时候会应用Spring配置的通知进行增强 -->
    <aop:pointcut expression="execution ( * services.*.*(..))" id="pc"/>
    <!-- 配置切面类的节点  作用主要就是整合通知和切入点 -->
    <aop:aspect ref="transactionManager">
        <aop:before method="beginTransaction" pointcut-ref="pc"/>
        <aop:after-returning method="commit" pointcut-ref="pc"/>
        <aop:after method="release" pointcut-ref="pc"/>
        <aop:after-throwing method="rollback" pointcut-ref="pc"/>
    </aop:aspect>
</aop:config>

修改测试类代码
在这里插入图片描述
执行结果
在这里插入图片描述

XML改注解(AOP)

使用注解介绍
@Aspect

@Pointcut

@Before 前置通知

@AfterReturning 后置通知

@After 最终通知

@AfterThrowing 异常通知

代码实现

删除XML中的AOPXML配置并注解代理模式

<!-- 注解  开启代理模式 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

注释事务管理器类:TransactionManager.java

package transaction;

@Component
@Aspect
public class TransactionManager {
    // 数据库连接工具类
    @Autowired
    private ConnectionUtils connectionUtils;

    @Pointcut("execution(* services.*.*(..))")
    private void transactionPointcut() {
    }

    /**
     * 开启事务
     */
    @Before("transactionPointcut()")
    public void beginTransaction() {
        try {
            System.out.println("开启事务");
            connectionUtils.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交事务
     */
    @AfterReturning("transactionPointcut()")
    public void commit() {
        try {
            System.out.println("提交事务");
            connectionUtils.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 回滚事务
     */
    @AfterThrowing("transactionPointcut()")
    public void rollback() {
        try {
            System.out.println("回滚事务");
            connectionUtils.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放连接
     */
    @After("transactionPointcut()")
    public void release() {
        try {
            System.out.println("释放连接");
            connectionUtils.getThreadConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        connectionUtils.removeConnection();
    }
}

执行结果
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值