SpringAOP
1.传统事务处理
- 创建java项目,导入坐标
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>springtransfer</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.15</version> </dependency> <dependency> <groupId>commons-dbutils</groupId> <artifactId>commons-dbutils</artifactId> <version>1.6</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>
- 编写Account实体类
package com.domain;
public class Account {
private int id;
private String name;
private double money;
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
- 编写AccountDao接口和实现类
package com.dao.impl; import com.dao.AccountDao; import com.utils.ConnectionUtils; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.SQLException; @Repository("accountDao") public class AccountDaoImp implements AccountDao { @Autowired private QueryRunner queryRunner; // 转出操作 public void outAccout(String outUser, double money){ String sql="update account set money = money - ? where name = ?"; try { queryRunner.update(sql,money,outUser); } catch (SQLException e) { e.printStackTrace(); } } // 转入操作 public void inAccout(String inUser, double money){ String sql="update account set money = money + ? where name = ?"; try { queryRunner.update(sql,money,inUser); } catch (SQLException e) { e.printStackTrace(); } } }
- 编写AccountService接口和实现类
@Service("accountService")
public class AccountServiceImp implements AccountService {
@Autowired
private AccountDao accountDao;
public void transfer(String outUser, String inUser, double money) {
accountDao.outAccout(outUser,money);
int i=1/0;
accountDao.inAccout(inUser,money);
}
}
- 编写spring核心配置文件
<?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: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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 导入配置文件--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!-- 开启注解扫描--> <context:component-scan base-package="com"></context:component-scan> <!--datasource--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!--QueryRunner--> <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner"> <constructor-arg name="ds" ref="dataSource"></constructor-arg> </bean> </beans>
- 编写测试代码
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:SpringContext.xml") public class testTransfer { @Autowired private AccountService accountService; @Test public void test(){ //未用到事务 accountService.transfer("tom", "jerry", 100d); } }
问题: 应该把业务逻辑控制在一个事务中,所以应该将事务挪到service层
解决方案:
- 编写线程绑定工具类
package com.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @Component public class ConnectionUtils { //先初始化 private ThreadLocal<Connection> threadLocal=new ThreadLocal<>(); @Autowired private DataSource dataSource; //获取线程连接,让他们处于同一个连接池 public Connection getThreadConnection(){ Connection connection = threadLocal.get(); if(connection==null){ try { connection = dataSource.getConnection(); threadLocal.set(connection); } catch (SQLException e) { e.printStackTrace(); } } return connection; } // 接触连接绑定 public void removeThreadConnection(){ threadLocal.remove(); } }
- 编写事务管理器
package com.utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.sql.Connection; import java.sql.SQLException; @Component public class TransactionManager { //事务管理器 @Autowired // 自动生成线程管理实例 private ConnectionUtils connectionUtils; // 实现开启事务 public void startTransaction() { Connection connection = connectionUtils.getThreadConnection(); try { connection.setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } // 实现事务提交 public void commit() { Connection connection = connectionUtils.getThreadConnection(); try { connection.commit(); } catch (SQLException e) { e.printStackTrace(); } } // 实现事务回滚 public void rollback() { Connection connection = connectionUtils.getThreadConnection(); try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } // 设置事务属性,释放资源 public void close() { Connection connection = connectionUtils.getThreadConnection(); try { connection.setAutoCommit(true);// 改回自动提交事务 connection.close();// 归还到连接池 connectionUtils.removeThreadConnection();// 解除线程绑定 } catch (SQLException e) { e.printStackTrace(); } } }
- 修改service层代码
package com.dao.impl; import com.dao.AccountDao; import com.utils.ConnectionUtils; import org.apache.commons.dbutils.QueryRunner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import java.sql.SQLException; @Repository("accountDao") public class AccountDaoImp implements AccountDao { @Autowired private QueryRunner queryRunner; // 处理事务时应该以连接池的方式,这样第一次使用时就会设置线程 @Autowired private ConnectionUtils connectionUtils; // 转出操作 public void outAccout(String outUser, double money){ String sql="update account set money = money - ? where name = ?"; try { queryRunner.update(connectionUtils.getThreadConnection(),sql,money,outUser); } catch (SQLException e) { e.printStackTrace(); } } // 转入操作 public void inAccout(String inUser, double money){ String sql="update account set money = money + ? where name = ?"; try { queryRunner.update(connectionUtils.getThreadConnection(),sql,money,inUser); } catch (SQLException e) { e.printStackTrace(); } } }
- 修改dao层代码
@Service("accountService")
public class AccountServiceImp implements AccountService {
@Autowired
private AccountDao accountDao;
@Autowired
private TransactionManager transactionManager;
public void transfer(String outUser, String inUser, double money) {
try {
transactionManager.startTransaction();
accountDao.outAccout(outUser,money);
int i=1/0;
accountDao.inAccout(inUser,money);
transactionManager.commit();
} catch (Exception e) {
transactionManager.rollback();
e.printStackTrace();
}finally {
transactionManager.close();
}
}
}
问题:业务层代码繁杂,重复代码多,业务层与事务控制方法耦合度高,违背了面向对象的开发思想
解决方案:代理模式,将业务代码和事务代码进行拆分,通过动态代理的方式,对业务方法进行事务的增强
- JDK动态代理: 基于接口的动态代理技术,目标对象必须实现了接口,与目标对象同级,实现拦截器invocationHandler加上反射机制生成一个代理接口的匿名类,在调用具体方法前会调用InvokeHandler来处理,实现方法的增强
package com.proxy; import com.service.AccountService; import com.utils.TransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @Component public class JdkProxyFactory { // JDK实现动态代理 @Autowired private AccountService accountService; @Autowired private TransactionManager transactionManager; public AccountService createAccountServiceProxy() { AccountService accountServiceProxy = null; // 参数1: 要加载的类的类加载器 // 要加载类的接口 // InvocationHandler实现类 accountServiceProxy = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() { //proxy 当前的代理对象 method对应的业务层方法 args传入的参数 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; try { //开启事务 transactionManager.startTransaction(); result = method.invoke(accountService, args); //提交事务 transactionManager.commit(); } catch (Exception e) { //回滚事务 transactionManager.rollback(); e.printStackTrace(); } finally { //释放资源 transactionManager.close(); } return result; } }); // 返回代理对象 return accountServiceProxy; } }
@Test public void testJDK() { AccountService accountServiceProxy = jdkProxyFactory.createAccountServiceProxy(); accountServiceProxy.transfer("tom", "jerry", 100d); }
- Cglib代理模式:基于父类的动态代理技术,动态的生成一个要代理的子类,子类重写要代理的类的所有不是final的方法,因此目标对象也不能是final类。子类中采用方法拦截技术拦截所有的父类方法的调用,顺势植入横切逻辑,对方法进行增强
package com.proxy; import com.service.AccountService; import com.utils.TransactionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @Component public class CglibProxyFactory { @Autowired private AccountService accountService; @Autowired private TransactionManager transactionManager; public AccountService createAccountServiceProxy(){ AccountService accountServiceProxy = null; //参数一:目标对象的字节码对象 //参数二:动作类,实现增强功能 accountServiceProxy = (AccountService) Enhancer.create(accountService.getClass(), new MethodInterceptor() { @Override //o 代表生成的代理对象 method代表调用方法的引用 objects 传入的参数 methodProxy代理方法 public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { Object result = null; try { //开启事务 transactionManager.startTransaction(); result = method.invoke(accountService, objects); //提交事务 transactionManager.commit(); } catch (Exception e) { //回滚事务 transactionManager.rollback(); e.printStackTrace(); } finally { //释放资源 transactionManager.close(); } return result; } }); return accountServiceProxy; } }
@Autowired private CglibProxyFactory cglibProxyFactory; @Test public void testCglib() { AccountService accountServiceProxy = cglibProxyFactory.createAccountServiceProxy(); accountServiceProxy.transfer("tom", "jerry", 100d); }
public void transfer(String outUser, String inUser, double money) { accountDao.outAccout(outUser,money); //int i=1/0; accountDao.inAccout(inUser,money); }
2.AOP
利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率
AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强
- 优点
- 在程序运行期间,在不修改源码的情况下对方法进行功能增强
- 逻辑清晰,开发核心业务的时候,不必关注增强业务的代码
- 减少重复代码,提高开发效率,便于后期维护
- 常用术语
- Target(目标对象):代理的目标对象
- Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
- Joinpoint(拦截点):所谓连接点是指那些可以被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接
- Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义
- Advice(通知/ 增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知分类:前置通知、后置通知、异常通知、最终通知、环绕通知
- Aspect(切面):是切入点和通知(引介)的结合
- Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入
- AOP开发事项
- 开发阶段: 编写核心业务代码(目标类的目标方法) 切入点; 把公用代码抽取出来,制作成通知(增强功能方法) 通知; 在配置文件中,声明切入点与通知间的关系即切面
- 运行阶段(Spring框架完成的):Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行
- 底层代理实现:在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。当bean实现接口时,会用JDK代理模式;当bean没有实现接口,用cglib实现( 可以强制使用cglib(在spring配置中加入<aop:aspectjautoproxy proxyt-target-class=”true”/>)
<!-- aspectj的织入(切点表达式需要用到该jar包) --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.13</version> </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: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"> <!--目标类交给IOC容器--> <bean id="accountService" class="com.lagou.service.impl.AccountServiceImpl"> </bean> <!--通知类交给IOC容器--> <bean id="myAdvice" class="com.lagou.advice.MyAdvice"></bean> <aop:config> <!--引入通知类--> <aop:aspect ref="myAdvice"> <!--配置目标类的transfer方法执行时,使用通知类的before方法进行前置增强--> <aop:before method="before" pointcut="execution(public void com.lagou.service.impl.AccountServiceImpl.transfer())"></aop:before> </aop:aspect> </aop:config> </beans>
- xml切点表达式execution([修饰符] 返回值类型 包名.类名.方法名(参数))
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号 * 代替,代表任意
- 包名与类名之间一个点 . 代表当前包下的类,两个点 .. 表示当前包及其子包下的类
- 参数列表可以使用两个点 .. 表示任意个数,任意类型的参数列表
- 切点表达式的抽取
<aop:config> <!--抽取的切点表达式--> <aop:pointcut id="myPointcut" expression="execution(* com.lagou.service..*.* (..))"> </aop:pointcut> <aop:aspect ref="myAdvice"> <aop:before method="before" pointcut-ref="myPointcut"></aop:before> </aop:aspect> </aop:config>
- xml通知类<aop:通知类型 method=“通知类中方法名” pointcut=“切点表达式"></aop:通知类型>
- 执行顺序 before==>afterreturning/afterthrowing==>after
- afterReturning与fterThrowing只有一个会出现
| 名称 | 标签 | 说明 |
| 前置通知 | <aop:before> | 用于配置前置通知。指定增强的方法在切入点方法之前执行 |
| 后置通知 | <aop:afterReturning> | 用于配置后置通知。指定增强的方法在切入点方法之后执行 |
| 异常通知 | <aop:afterThrowing> | 用于配置异常通知。指定增强的方法出现异常后执行 |
| 最终通知 | <aop:after> | 用于配置最终通知。无论切入点方法执行时是否有异常, 都会执行 |
| 环绕通知 | <aop:around> | 用于配置环绕通知。开发者可以手动控制增强代码在什么时候执行,通常独立使用 |
@Component @Aspect public class MyAdvice { @Before("execution(* com.lagou..*.*(..))") public void before() { System.out.println("前置通知..."); } }
<!--组件扫描--> <context:component-scan base-package="com.lagou"/> <!--aop的自动代理--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy
- 注解形式 切点表达式抽取
@Component @Aspect public class MyAdvice { @Pointcut("execution(* com.lagou..*.*(..))") public void myPoint(){} @Before("MyAdvice.myPoint()") public void before() { System.out.println("前置通知..."); }
- 注解形式通知类型:执行顺序@Before -> @After -> @AfterReturning(如果有异常:@AfterThrowing)
| 名称 | 标签 | 说明 |
| 前置通知 | @Before | 用于配置前置通知。指定增强的方法在切入点方法之前执行 |
| 后置通知 | @AfterReturning | 用于配置后置通知。指定增强的方法在切入点方法之后执行 |
| 异常通知 | @AfterThrowing | 用于配置异常通知。指定增强的方法出现异常后执行 |
| 最终通知 | @After | 用于配置最终通知。无论切入点方法执行时是否有异常,都会 执行 |
| 环绕通知 | @Around | 用于配置环绕通知。开发者可以手动控制增强代码在 |
@Configuration @ComponentScan("com.lagou") @EnableAspectJAutoProxy //替代 <aop:aspectj-autoproxy /> public class SpringConfig { }
浙公网安备 33010602011771号