SpringAOP

 

 

准备工作

 

drop database if exists spring_aop;

create database spring_aop;

use spring_aop;

create table account (
id int(11) auto_increment primary key,
accountNum varchar(20) default NULL,
money int(8) default 0
);

insert into account (accountNum, money) values
("622200001",1000),("622200002",1000);

 

开始导包

 

<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.13.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils -->
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>

 

配置自动扫包和数据源

 

<?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:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
https://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
">

<!-- bean definitions here -->
<context:component-scan base-package="dao"/>
<context:component-scan base-package="services"/>
<context:component-scan base-package="utils"/>

</beans>

------------------------------------------------------------
<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_aop"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>

 

配置完成后开始编写代码

package utils;

@Component
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
@Autowired
private ComboPooledDataSource dataSource;

public Connection getThreadConnection() {
try {
Connection conn = tl.get();
if (conn == null) {
conn = dataSource.getConnection();
tl.set(conn);
}
return tl.get();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

public void remove() {
tl.remove();
}
}
-------------------------
package entity;

public class Account {
private Integer id;
private String accountNum;
private Integer money;
}
-------------------------
package dao;

public interface AccountDao {
void updateAccount(Account account);
Account findAccountByNum(String accountNum);
}
-------------------------
package dao.impl;

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner runner;
@Autowired
private ConnectionUtils connectionUtils;
public void updateAccount(Account account) {
try {
runner.update(connectionUtils.getThreadConnection(),
"update account set accountNum=?,money=? where id=?",
account.getAccountNum(), account.getMoney(), account.getId());
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public Account findAccountByNum(String accountNum) {
List<Account> accounts = null;
try {
accounts = runner.query(connectionUtils.getThreadConnection(),
"select * from account where accountNum = ? ",
new BeanListHandler<Account>(Account.class),
accountNum);
} catch (SQLException e) {
throw new RuntimeException(e);
}
if (accounts == null || accounts.size() == 0) {
return null;
} else if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一,数据有问题");
} else {
return accounts.get(0);
}
}
}
-----------------------------
age services;

public interface AccountService {
void transfer(String sourceAccount, String targetAccount, Integer money);

}
-----------------------------
package services.impl;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

@Autowired
private AccountDao accountDao;

public void transfer(String sourceAccount, String targetAccount, Integer money) {
Account source = accountDao.findAccountByNum(sourceAccount);
Account target = accountDao.findAccountByNum(targetAccount);
source.setMoney(source.getMoney() - money);
target.setMoney(target.getMoney() + money);
accountDao.updateAccount(source);
accountDao.updateAccount(target);
System.out.println("转账完毕");
}
}
-----------------------------
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class AccountTest {

@Autowired
private AccountService accountService;

@Test
public void testTransfer() {
accountService.transfer("622200001", "622200002", 100);
}
}
-----------------------------
使用事物管理器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().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;
public AccountService getAccountService() {
return (AccountService) Proxy.newProxyInstance(
accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
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();
}
}
});

}
}
-----------------------------
最后添加事务管理bean

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

配置代理Service

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

Account模块测试类:AccountTest.java

将原本引入的AccountService实例改为AccountService的事务代理对象

@Qualifier("transactionProxyAccountService")

 

引入AOP(XML)

  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>
  1. 配置文件中添加 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)

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

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

  1. 注释事务管理器类: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();
}
}
posted on 2021-03-28 13:16  SpringTrap  阅读(398)  评论(0)    收藏  举报