本文将使用大量篇幅介绍基于接口的动态代理,通过两个实例做出详细介绍,从而解释Spring Aop的实现过程。
动态代理
什么是代理?
代理的概念很好理解,在实际生活中随处可见,电脑城的店铺是某品牌的代理,茅台经销商是茅台的代理,等等。
在Java中代理主要分为动态代理和静态代理,而动态代理又分为基于接口的动态代理和基于子类的动态代理。本文主要从动态代理的基于接口的动态代理的视角来看Spring框架的AOP,以及对事务的控制。
那么什么是动态代理呢?从用途上来理解:动态代理可以在不改变源代码的情况下,为类或方法增加额外的功能。动态代理的两种类型:
- 基于接口的动态代理:是JDK官方提供的一种代理模式。一般使用Proxy的newProxyInstance方法创建,下面是创建该代理的方法:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,InvocationHandler h)
throws IllegalArgumentException
此处涉及的三个参数,后文实例中将有介绍.
特此提出一点:被代理的类必须实现一个接口,否则不能使用基于JDK的动态代理
2. 基于子类的动态代理:这种模式主要是由第三方提供的cglib库,涉及到的类为:Enhancer。本文不打算介绍这种代理,故此不表。
动态代理实例1:
基于JDK的动态代理必须实现一个接口,所以此处提供 一个接口及其实现类:
public interface Producer {
/**
* 销售
* @param money
*/
public void saleProduct(float money);
/**
* 售后
* @param money
*/
public void afterService(float money);
}
public class ProducerImpl implements Producer{
/**
* 销售
* @param money
* 传入的参数为售价
*/
public void saleProduct(float money){
System.out.println("销售产品,并拿到钱:"+money);
}
/**
* 售后
* 传入的参数为售后服务费用
* @param money
*/
public void afterService(float money){
System.out.println("提供售后服务,并拿到钱:"+money);
}
}
如下是动态代理的实现:
public class Consumer{
public static void main(String[] args) {
final Producer producer = new Producer();
Producer proxyProducer = (Producer) Proxy.newProxyInstance(producer.getClass().getClassLoader(),
producer.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//提供增强的代码
Object returnValue = null;
//1.获取方法执行的参数
Float money = (Float)args[0];
//2.判断当前方法是不是销售,如果是销售则增加功能
if("saleProduct".equals(method.getName())) {
returnValue = method.invoke(producer, money*0.8f);
}
return returnValue;
}
});
proxyProducer.saleProduct(10000f);
}
}
上面的代码在未改变源代码的情况下实现了对Producer的销售方法的增强,使其输出的销售收入为售价的0.8,运行结果为
销售产品,并拿到钱:8000.0
这里回到前面所提到的创建动态代理对象所需要的三个参数:
- ClassLoader loader:该参数翻译过来为“类加载器”,它是用于加载代理对象字节码的,目的是和被代理对象使用相同的类加载器,一般为固定写法:producer.getClass().getClassLoader(),producer处为代理对象的类名;
- Class<?>[] interfaces:需要传入一个节码数组,它是用于让代理对象和被代理对象有相同方法,一般也是固定写法:producer.getClass().getInterfaces(),producer同上;
- InvocationHandler h :此参数是动态代理的核心处。InvocationHandler 是一个接口类,此处使用匿名内部类的方式实现了该接口。而该接口也需要传入三个参数,分别为:
- Object proxy:代理对象的引用,并无太大实际意义
- Method method:当前执行的方法。即,需要对哪些方法进行增强
- Object[] args:当前执行方法所需要的参数
实例2:事务控制
下面将通过一个基于xml配置的转账实例介绍基于接口的动态代理在事务控制的应用
/**
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
/**
* 账户的持久层接口
*/
public interface AccountDao {
/**
* 根据id查询
* @return
*/
Account findAccountById(Integer accountId);
/**
* 根据名称查询账户
* @param accountName
* @return 如果有唯一的一个结果就返回,如果没有结果就返回null
* 如果结果集超过一个就抛异常
*/
Account findAccountByName(String accountName);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
}
/**
* 账户的持久层实现类
*/
public class AccountDaoImpl implements AccountDao {
private QueryRunner runner ;
private ConnectionUtils connectionUtils ;
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
@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 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);
}
}
@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);
}
}
}
/**
* 账户的业务层接口
*/
public interface AccountService {
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName,String targetName,Float money);
}
/**
* 账户的业务层实现类
*/
public class AccountServiceImpl implements AccountService{
private AccountDao accountDao ;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
return accountDao.findAccountById(accountId);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//2.1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney()-money);
//2.4转入账户加钱
target.setMoney(target.getMoney()+money);
//2.5更新转出账户
accountDao.updateAccount(source);
int i=1/0;
//2.6更新转入账户
accountDao.updateAccount(target);
}
}
编写测试类:
@Test
public void m(){
ApplicationContext ac = new ClassPathXmlApplicationContext("a.xml");
AccountService as = ac.getBean("accountService", AccountService.class);
as.transfer("aaa","bbb",100f);
}
PS:本文并不会为单项操作提供单独的xml配置,会在文章最终提供一个综合xml配置文件。
运行上面的代码,查看数据库:
运行前的数据库
运行后的数据库
发现,转出账户减少了100,但转入账户并未增加100。在更新转入账户之前,人为制造了一个异常,由于转账方法并未对事务加以控制,结果在意料之中。
下面我们对AccountServiceImpl加上事务控制
public class AccountServiceImp2 implements AccountService{
private AccountDao accountDao;
private TransactionManager txManager;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public Account findAccountById(Integer accountId) {
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
Account account = accountDao.findAccountById(accountId);
//3.提交事务
txManager.commit();
//4.返回结果
return account;
}catch (Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放连接
txManager.release();
}
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
//2.1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3转出账户减钱
source.setMoney(source.getMoney()-money);
//2.4转入账户加钱
target.setMoney(target.getMoney()+money);
//2.5更新转出账户
accountDao.updateAccount(source);
int i=1/0;
//2.6更新转入账户
accountDao.updateAccount(target);
//3.提交事务
txManager.commit();
}catch (Exception e){
//4.回滚操作
txManager.rollback();
e.printStackTrace();
}finally {
//5.释放连接
txManager.release();
}
}
上述代码中的两个工具类如下:
**
* 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
*/
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection() {
try{
//1.先从ThreadLocal上获取
Connection conn = tl.get();
//2.判断当前线程上是否有连接
if (conn == null) {
//3.从数据源中获取一个连接,并且存入ThreadLocal中
conn = dataSource.getConnection();
tl.set(conn);
}
//4.返回当前线程上的连接
return conn;
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}
**
* 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
*/
public class TransactionManager {
private ConnectionUtils connectionUtils ;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();// 把连接和当前线程解绑
}catch (Exception e){
e.printStackTrace();
}
}
}
编写测试代码:
@Test
public void m(){
ApplicationContext ac = new ClassPathXmlApplicationContext("a.xml");
AccountService as = ac.getBean("accountServiceProxy", AccountService.class);
as.transfer("aaa","bbb",100f);
}
添加事务管理之后,我们发现出现异常之后事务控制住了,并不会出现上述情况,结果就不加以展示了。
虽然,上述方法成功的控制住了事务,但我们发现有两点不足之处:
- 对事务的控制必须修改源代码才能实现;
- 当需要事务控制的方法有很多时,每个方法都需要去修改,工程量较大。
由于AccountServiceImpl2的缺点太多,所以后续都不会使用该类作为AccountService接口的实现类,而使用AccountServiceImpl类作为AccountService接口的实现类。
故,此处可使用动态代理来实现在不修改源码的情况下,实现事务控制:
/**
* 用于创建Service的代理
*
*
*/
public class ServiceProxy {
private AccountService accountService ;
private TransactionManager txManager ;
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public final void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
/**
* 获取Service代理对象
* @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
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue = null;
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
rtValue = method.invoke(accountService, args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
} catch (Exception e) {
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
//6.释放连接
txManager.release();
}
}
});
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置代理的service-->
<bean id="accountServiceProxy" factory-bean="serviceProxy" factory-method="getAccountService"></bean>
<!--配置beanfactory-->
<bean id="serviceProxy" class="com.aaa.factory.ServiceProxy">
<!-- 注入service -->
<property name="accountService" ref="accountService"></property>
<!-- 注入事务管理器 -->
<property name="txManager" ref="txManager"></property>
</bean>
<!-- 配置Service -->
<bean id="accountService" class="com.aaa.service.impl.AccountServiceImpl">
<!-- 注入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置Dao对象-->
<bean id="accountDao" class="com.aaa.dao.impl.AccountDaoImpl">
<!-- 注入QueryRunner -->
<property name="runner" ref="runner"></property>
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/aa"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 配置Connection的工具类 ConnectionUtils -->
<bean id="connectionUtils" class="com.aaa.utils.ConnectionUtils">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器-->
<bean id="txManager" class="com.aaa.utils.TransactionManager">
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
</beans>
将数据库调回到最初的状态
运行下面的代码:
@Test
public void m(){
ApplicationContext ac = new ClassPathXmlApplicationContext("a.xml");
AccountService as = ac.getBean("accountServiceProxy", AccountService.class);
as.transfer("aaa","bbb",100f);
}
值得注意的一点是:当使用基于接口的动态代理时,创建实例时要以接口的类型去创建,否则会报错
由于在AccountServiceImp类的transfer方法中人为制造了一个异常,运行出现了预期的异常,并且数据库数据并未改变:
Caused by: java.lang.ArithmeticException: / by zero
at com.aaa.service.impl.AccountServiceImpl.transfer(AccountServiceImpl.java:63)
... 29 more
从上述实例可以看出动态代理的优势,而Spring的AOP也是基于动态代理实现的。当理解了动态代理后,Spring AOP也就没有太大难度了。
Spring AOP的一些术语解释:
-
JoinPoint(连接点):作为连接点是指那些被拦截到的点。在spring中,这些连接点指的是方法,spring只支持方法类型的连接点。通俗讲,连接点即被代理类的所有方法,也就是本例中AccountServiceImpl的所有方法。
-
Pointcut(切入点):所谓切入点是指要对哪些JoinPoint进行拦截的定义。即,要被增强处理的方法。以本例为例:若将内部类的invoke方法变为:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("findAccountById".equals(method.getName())) {
return method.invoke(accountService, args);
}
Object rtValue = null;
try {
txManager.beginTransaction();//1.开启事务
//2.执行操作
rtValue = method.invoke(accountService, args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
} catch (Exception e) {
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
txManager.release();//6.释放连接
}
}
则切入点为除了findAccountById方法以外的所有方法;
-
advice(通知):个人更喜欢翻译为“增强处理”,所谓advice是指拦截到JoinPoint之后所要做的事情(即,动态代理中的内部类中的重写的**方法**中所要做的事情,在本例中,TransactionManager类就是advice,用于为拦截到的方法开启事务支持),而advice的类型有:
在advice中,有明确的通过反射执行被代理类的方法
- 前置advice:在显示调用业务方法之前执行的代码
- 后置advice:(有翻译为:返回通知)在显示调用业务方法之后执行的代码
- 异常advice:在异常处理中执行的代码
- 最终advice:(有翻译为:后置通知)在finally块中执行的代码
- 环绕advice:整个动态代理内部类的重写方法即为环绕advice
看下面的图可能会更好理解:
值得提出的一点是,after-returning advice和after-throwing advice不能同时出现。从本例中也可看出,当事务提交就不能进行事务回滚,事务回滚就不能事务提交;
-
Target(目标对象):即被代理对象,也就是本例中的AccountServiceImpl;
-
Proxy(代理):代理对象,也就是本例中的ServiceProxy;
-
weaving(织入):是指把增强处理应用到目标对象来创建新的代理对象的过程。TransactionManager应用到AccountServiceImpl创建代理对象ServiceProxy的过程
-
Aspect(切面):是切入点和增强处理的结合。
根据上述的概念,可利用Spring AOP来实现事务案例:
- 删除代理对象ServiceProxy;
- 将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"
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">
<!-- 配置Service -->
<bean id="accountService" class="com.aaa.service.impl.AccountServiceImpl">
<!-- 注入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
<!--配置Dao对象-->
<bean id="accountDao" class="com.aaa.dao.impl.AccountDaoImpl">
<!-- 注入QueryRunner -->
<property name="runner" ref="runner"></property>
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"></bean>
<!-- 配置数据源 -->
<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/eesy"></property>
<property name="user" value="root"></property>
<property name="password" value="1234"></property>
</bean>
<!-- 配置Connection的工具类 ConnectionUtils -->
<bean id="connectionUtils" class="com.aaa.utils.ConnectionUtils">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器-->
<bean id="txManager" class="com.aaa.utils.TransactionManager">
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<!--配置aop-->
<aop:config>
<!--配置通用切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.aaa.service.impl.*.*(..))"></aop:pointcut>
<aop:aspect id="txAdvice" ref="txManager">
<!--配置前置通知:开启事务-->
<aop:before method="beginTransaction" pointcut-ref="pt1"></aop:before>
<!--配置后置通知:提交事务-->
<aop:after-returning method="commit" pointcut-ref="pt1"></aop:after-returning>
<!--配置异常通知:回滚事务-->
<aop:after-throwing method="rollback" pointcut-ref="pt1"></aop:after-throwing>
<!--配置最终通知:释放连接-->
<aop:after method="release" pointcut-ref="pt1"></aop:after>
</aop:aspect>
</aop:config>
</beans>
从上述实例来看,当我们对Java的动态代理有一定了解之后,可以更好的帮助我们去理解SPring的AOP机制。
本人是Java的初学者,首次接触spring框架,知识储备有限,错误之处请见谅并加以指点!!