【实例】使用Spring AOP进行业务增强(通过注解的方式)

以下代码通过了编译,可以直接运行(需要更改包名)

目的: 通过Spring AOP实现对service的transfer(转账)操作增加事务处理。

  • 增强类MyAdvice
package com.bamzhy.advice;

import com.bamzhy.utils.MyC3P0DataSouce;
import com.bamzhy.utils.TransactionManagement;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Aspect
@Component
public class MyAdvice  {

    //设置好增强点
    @Pointcut("execution (public boolean com.bamzhy.service.UserServiceImpl.transfer(..)) throws java.sql.SQLException )")
    private void myPointCut(){
    }

    //around方法
    @Around("myPointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed=null;
        boolean ret=false;
        Connection connection=null;
        try{
            connection= MyC3P0DataSouce.getConnection();
            //开启事务
            connection.setAutoCommit(false);
            //这里是核心
            proceed=joinPoint.proceed();
            connection.commit();
            connection.close();
            ret=true;
            System.out.println("这里是增强代码");
        }catch (Exception e){
            e.printStackTrace();
            if(connection!=null){
                try{
                    connection.rollback();
                }catch (SQLException e1){
                    e1.printStackTrace();
                }
            }
        }
        return proceed;
    }
}
  • 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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--设定扫描的包名-->
    <context:component-scan base-package="com.bamzhy"/>
    <aop:aspectj-autoproxy />
</beans>
  • service层
package com.bamzhy.service;

import com.bamzhy.bean.Account;
import com.bamzhy.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;

//service层,实例化时getBean调用这个id
@Service("service")
public class UserServiceImpl implements UserService {
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
    //自动去UserDao和其子类中(@Repository)寻找实例化对象并注入
    @Autowired
    private UserDao userDao;

    @Override
    public boolean transfer(String usernameFrom, String usernameTo, int money) throws SQLException {
        Account accountFrom = userDao.getAccount(usernameFrom);
        Account accountTo = userDao.getAccount(usernameTo);
        accountFrom.setMoney(accountFrom.getMoney()-money);
        accountTo.setMoney(accountTo.getMoney()+money);
        if (!userDao.updateAccount(accountFrom))
            return false;
        //int i = 1/0;
        if (!userDao.updateAccount(accountTo))
            return false;
        return true;
    }
}
  • dao层
package com.bamzhy.dao;

import com.bamzhy.bean.Account;
import com.bamzhy.utils.TransactionManagement;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;

//Dao层
@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public boolean updateAccount(Account account) throws SQLException {
        QueryRunner queryRunner=new QueryRunner();
        String sql="update homework set money = ? where username = ?;";
        //public int update(Connection conn, String sql, Object... params)
        int update = queryRunner.update(TransactionManagement.getConnection(),sql,account.getMoney(), account.getUsername());
        return update==1?true:false;
    }

    @Override
    public Account getAccount(String username) throws SQLException {
        QueryRunner queryRunner=new QueryRunner();
        String sql="select * from homework where username = ?;";
        Account query = queryRunner.query(TransactionManagement.getConnection(), sql, new BeanHandler<Account>(Account.class), username);
        return query;
    }
}
  • test文件
package com.bamzhy.test;
import com.bamzhy.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.SQLException;

public class test {
    @Test
    public void test1() throws SQLException {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) applicationContext.getBean("service");
        service.transfer("haha1","haha2",1000);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值