JAVA--AOP(面向切面编程)

AOP的相关概念

  • 概述:
      在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。----百度百科
  • 作用(我的理解):
      就是把程序中重复的代码抽离出来,通过动态代理的方式在不修改原码的前提下,实现对方法的增强。
  • 优势:
      减少重复的代码,提高开发效率,维护方便
  • 实现方式:
      动态代理技术
  • AOP相关的术语
    1. Joinpoint(连接点):
        所谓连接点是指那些被拦截到的点。在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点(我的理解是目标类的所有方法)
    2. Advice(通知/增强):
        所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知(动态代理中的功能增强)
        通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
    3. Introduction(引介):
        引介是一种特殊的通知在不修改类代码的前提下, Introduction 可以在运行期为类动态地添加一些方 法或 Field。
    4. Target(目标对象):
        代理的目标对象
    5. Weaving(织入):
        是指把增强应用到目标对象来创建新的代理对象的过程(增强后的对象)
        spring 采用动态代理织入,而 AspectJ 采用编译期织入和类装载期织入
    6. Proxy(代理):
        一个类被 AOP 织入增强后,就产生一个结果代理类
    7. Aspect(切面):
        是切入点和通知(引介)的结合

具体案例(通过注解的方式配置Spring实现银行的curd操作)

  • 创建银行账户实体类Account
@Data
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;
}
  • 创建持久层接口实现类AccountDaoImpl
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;
    @Autowired
    private ConnectionUtils connectionUtils;
    
    @Override
    public List<Account> findAllAccount() {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ?",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void saveAccount(Account account) {
        try{
            runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateAccount(Account account) {
        try{
            runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteAccount(Integer accountId) {
        try{
            runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountByName(String accountName) {
        try{
            List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);
            if(accounts == null || accounts.size() == 0){
                return null;
            }
            if(accounts.size() > 1){
                throw new RuntimeException("结果集不唯一,数据有问题");
            }
            return accounts.get(0);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
  • 创建服务层接口实现类AccountServiceImpl(位置有限只写了2个方法)
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;
    @Autowired
    private TransactionManager transactionManager;

    @Override
    public void saveAccount(Account account) {
        try {
            // 开启事务
            txManager.beginTransaction();
            // 执行操作
            accountDao.saveAccount(account);
            // 提交事务
            txManager.commit();
        }catch (Exception e){
            // 回滚操作
            txManager.rollback();
        }finally {
            // 释放连接
            txManager.release();
        }
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        try {
            // 开启事务
            transactionManager.beginTransaction();
            // 执行操作,根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            // 根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            // 转出账户减钱
            source.setMoney(source.getMoney() - money);
            // 转入账户加钱
            target.setMoney(target.getMoney() + money);
            // 更新转出账户
            accountDao.updateAccount(source);
			// 假设转账异常
            //int i=1/0;
            // 更新转入账户
            accountDao.updateAccount(target);
            // 提交事务
            transactionManager.commit();
        } catch (Exception e) {
            // 回滚操作
            transactionManager.rollback();
            e.printStackTrace();
        } finally {
            // 释放连接
            transactionManager.release();
        }
    }
}
  • 创建连接工具类ConnectionUtils,通过连接和线程绑定来控制事务(控制转账操作为一条连接)
@Component
public class ConnectionUtils {

    private ThreadLocal<Connection> t = new ThreadLocal<Connection>();
    @Autowired
    private DataSource dataSource;
    public Connection getThreadConnection(){
        try{
            //从ThreadLocal上获取连接
            Connection con = t.get();
            // 判断是否有连接
            if (con == null){
                // 从数据源中获取一个连接,并且存入ThreadLocal中
                con = dataSource.getConnection();
                t.set(con);
            }
            return con;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    // 把连接和线程解绑
    public void removeConnection(){
        t.remove();
    }
}
  • 分析:
    1. 省略了持久层的接口、服务层的接口、全局配置类、数据库配置类、maven依赖(spring-context、spring-test、c3p0、junit、dbutils、mysql、lombok)
    2. 上面的服务层代码,在服务层AccountServiceImpl中的方法,可以看出2个方法中有比较多重复的代码,都是事务控制的代码,在实际项目中可能有几十个方法,如果突然要改事务控制方法的代码(比如改方法名),这几十个方法都需要修改,因此我们需要用AOP技术进行编写。

用AOP进行代码改造

  • 创建工厂类BeanFactory(动态代理),先了解动态代理帮助理解
@Component
public class BeanFactory {
    @Autowired
    private IAccountService accountService;
    @Autowired
    private TransactionManager transactionManager;

    public IAccountService getAccountService() {
        return (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        Object rtValue = null;
                        try {
                        	// 开启事务
                            transactionManager.beginTransaction();
                            // accountService在这里是目标类,在执行之前进行功能增强
                            // method是目标类的方法
                            rtValue = method.invoke(accountService,objects);
                            // 提交事务
                            transactionManager.commit();
                            return rtValue;
                        }catch (Exception e){
                        	// 回滚事务
                            transactionManager.rollback();
                            throw new RuntimeException(e);
                        }finally {
                        	// 释放连接
                            transactionManager.release();
                        }
                    }
                });
    }
}
  • 创建事务管理类
@Component
public class TransactionManager {
    @Autowired
    private ConnectionUtils connectionUtils;
    // 开启事务
    public  void beginTransaction(){
        try {
            System.out.println("前置");
            connectionUtils.getThreadConnection().setAutoCommit(false);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

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

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

    // 释放连接
    public  void release(){
        try {
            System.out.println("最终");
            connectionUtils.getThreadConnection().close();//还回连接池中
            connectionUtils.removeConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
  • 改造服务层AccountServiceImpl实现类的代码
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;
    @Autowired
    private TransactionManager transactionManager;

    @Override
    public void saveAccount(Account account) {
            accountDao.saveAccount(account);
    }

    @Override
    public void transfer(String sourceName, String targetName, Float money) {
       System.out.println("transfer....");
        // 根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        // 根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        // 转出账户减钱
        source.setMoney(source.getMoney() - money);
        // 转入账户加钱
        target.setMoney(target.getMoney() + money);
        // 更新转出账户
        accountDao.updateAccount(source);
        // 模拟转账出错
		// int i=1/0;
        // 更新转入账户
        accountDao.updateAccount(target);
    }
}
  • 调用方法
@Test
    public void testTransferByProxy(){
    	// 调用BeanFactory类的getAccountService,获取动态代理产生的对象
        beanFactory.getAccountService().transferByProxy("aaa","bbb",100f);
    }	
  • 分析:
      通过动态代理的方式,让java帮我们创建创建代理类,当通过动态代理产生的对象调用目标类(这里指AccountServiceImpl类)的方法时,该方法就会实现功能增强(这里指的事务控制)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值