坐标:
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>commons-dbutils</groupId><artifactId>commons-dbutils</artifactId><version>1.4</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>
创建实体类daomain
/*** 账户的实体类*/public class Account implements Serializable {private Integer id;private String name;private Float money;}
创建接口AccountDao.java
/*** 账户的持久层接口*/public interface AccountDao {/*** 查询所有* @return*/List<Account> findAllAccount();/*** 查询一个* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 删除* @param acccountId*/void deleteAccount(Integer acccountId);/*** 根据名称查询账户* @param accountName* @return 如果有唯一的一个结果就返回,如果没有结果就返回null* 如果结果集超过一个就抛异常*/Account findAccountByName(String accountName);}
创建实现类AccountDaoImpl.java
/*** 账户的持久层实现类*/public class AccountDaoImpl implements AccountDao {private QueryRunner runner;public List<Account> findAllAccount() {try{return runner.query("select * from account",new BeanListHandler<Account>(Account.class));}catch (Exception e) {throw new RuntimeException(e);}}public Account findAccountById(Integer accountId) {try{return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);}catch (Exception e) {throw new RuntimeException(e);}}public void saveAccount(Account account) {try{runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());}catch (Exception e) {throw new RuntimeException(e);}}public void updateAccount(Account account) {try{runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());}catch (Exception e) {throw new RuntimeException(e);}}public void deleteAccount(Integer accountId) {try{runner.update("delete from account where id=?",accountId);}catch (Exception e) {throw new RuntimeException(e);}}public Account findAccountByName(String accountName) {try{List<Account> accounts = runner.query("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);}}}
建接口AccountService.java
/*** 账户的业务层接口*/public interface AccountService {/*** 查询所有* @return*/List<Account> findAllAccount();/*** 查询一个* @return*/Account findAccountById(Integer accountId);/*** 保存* @param account*/void saveAccount(Account account);/*** 更新* @param account*/void updateAccount(Account account);/*** 删除* @param acccountId*/void deleteAccount(Integer acccountId);/*** 转账* @param sourceName 转出账户名称* @param targetName 转入账户名称* @param money 转账金额*/void transfer(String sourceName, String targetName, Float money);}
创建接口的实现类,AccountServiceImpl.java
/*** 账户的业务层实现类** 事务控制应该都是在业务层*/public class AccountServiceImpl implements AccountService {private AccountDao accountDao;public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public List<Account> findAllAccount() {return accountDao.findAllAccount();}public Account findAccountById(Integer accountId) {return accountDao.findAccountById(accountId);}public void saveAccount(Account account) {accountDao.saveAccount(account);}public void updateAccount(Account account) {accountDao.updateAccount(account);}public void deleteAccount(Integer acccountId) {accountDao.deleteAccount(acccountId);}public void transfer(String sourceName, String targetName, Float money) {System.out.println("transfer....");//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);}}
配置applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 配置Service --><bean id="accountService" class="com.it.service.impl.AccountServiceImpl"><!-- 注入dao --><property name="accountDao" ref="accountDao"></property></bean><!--配置Dao对象--><bean id="accountDao" class="com.it.dao.impl.AccountDaoImpl"><!-- 注入QueryRunner --><property name="runner" ref="runner"></property></bean><!--配置QueryRunner--><bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype"><constructor-arg name="ds" ref="dataSource"></constructor-arg></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/itcastspring"></property><property name="user" value="root"></property><property name="password" value="root"></property></bean></beans>
测试AccountServiceTest.java
/*** 使用Junit单元测试:测试我们的配置*/@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:applicationContext.xml")public class AccountServiceTest {@Autowiredprivate AccountService as;@Testpublic void testTransfer(){as.transfer("aaa","bbb",100f);}}
事务被自动控制了。换言之,我们使用了connection对象的setAutoCommit(true)

如果在AccountServiceImpl.java中的transfer方法中,抛出一个异常。此时事务不会回滚,原因是DBUtils每个操作数据都是获取一个连接,每个连接的事务都是独立的,且默认是自动提交。
解决方案:
需要使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只能有一个能控制事务的连接对象。
ConnectionUtils.java
/*** 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定*/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();}}
TransactionManager.java
和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
/*** 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接*/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();}}}
配置AccountDaoImpl.java
注入连接工具对象,使得操作数据库从同一个连接中获取
/*** 账户的持久层实现类*/public class AccountDaoImpl implements AccountDao {private QueryRunner runner;private ConnectionUtils connectionUtils;public void setConnectionUtils(ConnectionUtils connectionUtils) {this.connectionUtils = connectionUtils;}public void setRunner(QueryRunner runner) {this.runner = runner;}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);}}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);}}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);}}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 void deleteAccount(Integer accountId) {try{runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);}catch (Exception e) {throw new RuntimeException(e);}}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.java
事务操作一定需要在Service层控制。
作用:注入事务管理器对象,对每个操作都需要开启事务、提交事务、关闭事务,如果抛出异常,需要回滚事务。
/*** 账户的业务层实现类** 事务控制应该都是在业务层*/public class AccountServiceImpl implements AccountService {private AccountDao accountDao;private TransactionManager txManager;public void setTxManager(TransactionManager txManager) {this.txManager = txManager;}public void setAccountDao(AccountDao accountDao) {this.accountDao = accountDao;}public List<Account> findAllAccount() {try {//1.开启事务txManager.beginTransaction();//2.执行操作List<Account> accounts = accountDao.findAllAccount();//3.提交事务txManager.commit();//4.返回结果return accounts;}catch (Exception e){//5.回滚操作txManager.rollback();throw new RuntimeException(e);}finally {//6.释放连接txManager.release();}}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();}}public void saveAccount(Account account) {try {//1.开启事务txManager.beginTransaction();//2.执行操作accountDao.saveAccount(account);//3.提交事务txManager.commit();}catch (Exception e){//4.回滚操作txManager.rollback();}finally {//5.释放连接txManager.release();}}public void updateAccount(Account account) {try {//1.开启事务txManager.beginTransaction();//2.执行操作accountDao.updateAccount(account);//3.提交事务txManager.commit();}catch (Exception e){//4.回滚操作txManager.rollback();}finally {//5.释放连接txManager.release();}}public void deleteAccount(Integer acccountId) {try {//1.开启事务txManager.beginTransaction();//2.执行操作accountDao.deleteAccount(acccountId);//3.提交事务txManager.commit();}catch (Exception e){//4.回滚操作txManager.rollback();}finally {//5.释放连接txManager.release();}}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();}}}
配置applicationContext.xml
<!-- 配置Service --><bean id="accountService" class="com.it.service.impl.AccountServiceImpl"><!-- 注入dao --><property name="accountDao" ref="accountDao"></property><!--注入事务管理器--><property name="txManager" ref="txManager"></property></bean><!--配置Dao对象--><bean id="accountDao" class="com.it.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"><!--这里要去掉queryRunner的默认连接池配置,由ConnectionUtils 获取连接--><!--<constructor-arg name="ds" ref="dataSource"></constructor-arg>--></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/itcastspring"></property><property name="user" value="root"></property><property name="password" value="root"></property></bean><!-- 配置Connection的工具类 ConnectionUtils --><bean id="connectionUtils" class="com.it.utils.ConnectionUtils"><!-- 注入数据源--><property name="dataSource" ref="dataSource"></property></bean><!-- 配置事务管理器--><bean id="txManager" class="com.it.utils.TransactionManager"><!-- 注入ConnectionUtils --><property name="connectionUtils" ref="connectionUtils"></property></bean>
通过对业务层改造,已经可以实现事务控制了,但是由于我们添加了事务控制,也产生了一个新的问题:
业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了。
试想一下,如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层实现类可能有十几个甚至几十个。
【思考】:
这个问题能不能解决呢?
答案是肯定的,使用下一小节中提到的技术

AOP (Aspect Oriented Programing) 称为:面向切面编程,它是一种编程思想。
AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码的编写方式(应用场景:例如性能监视、事务管理、安全检查、缓存、日志记录等)。
【扩展了解】AOP 是 OOP(面向对象编程(Object Oriented Programming,OOP,面向对象程序设计)是一种计算机编程架构),思想延续 !

代理机制。
2个:spring的aop的底层原理
1:JDK代理(要求目标对象面向接口)(spring默认的代理方式是JDK代理)
2:CGLIB代理(面向接口、面向类)
Joinpoint(连接点): (方法)
所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。
Pointcut(切入点): (方法)
所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。
Advice(通知/增强): (方法)
所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。Aspect(切面): (类)
是切入点和通知(引介)的结合。

坐标xml
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency>
定义Service的接口和实现类,创建接口AccountService.java
*** 账户的业务层接口*/public interface AccountService {/*** 模拟保存账户*/void saveAccount();/*** 模拟更新账户* @param i*/void updateAccount(int i);/*** 删除账户* @return*/int deleteAccount();}
创建接口的实现类AccountServiceImpl.java
*** 账户的业务层实现类*/public class AccountServiceImpl implements AccountService {public void saveAccount() {System.out.println("执行了保存");}public void updateAccount(int i) {System.out.println("执行了更新"+i);}public int deleteAccount() {System.out.println("执行了删除");return 0;}}
创建增强类Logger.java
/*** 用于记录日志的工具类,它里面提供了公共的代码*/public class Logger {/*** 用于打印日志:计划让其在切入点方法执行之前执行(切入点方法就是业务层方法)*/public void printLog(){System.out.println("Logger类中的pringLog方法开始记录日志了。。。");}}
配置applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 配置srping的Ioc,把service对象配置进来--><bean id="accountService" class="com.it.service.impl.AccountServiceImpl"></bean><!--spring中基于XML的AOP配置步骤1、把通知Bean也交给spring来管理2、使用aop:config标签表明开始AOP的配置3、使用aop:aspect标签表明配置切面id属性:是给切面提供一个唯一标识ref属性:是指定通知类bean的Id。4、在aop:aspect标签的内部使用对应标签来配置通知的类型我们现在示例是让printLog方法在切入点方法执行之前执行:所以是前置通知aop:before:表示配置前置通知method属性:用于指定Logger类中哪个方法是前置通知pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强切入点表达式的写法:关键字:execution(表达式)--><!-- 配置Logger类,声明切面(创建对象,不是真正aop的切面) --><bean id="logger" class="com.it.utils.Logger"></bean><!--配置AOP--><aop:config><!--配置切面 --><aop:aspect id="logAdvice" ref="logger"><!-- 配置通知的类型,并且建立通知方法和切入点方法的关联--><aop:before method="printLog" pointcut="execution(void com.it.service.impl.AccountServiceImpl.saveAccount())"></aop:before><aop:before method="printLog" pointcut="execution(void com.it.service.impl.AccountServiceImpl.updateAccount(int))"></aop:before><aop:before method="printLog" pointcut="execution(int com.it.service.impl.AccountServiceImpl.deleteAccount())"></aop:before></aop:aspect></aop:config></beans>

测试
/*** 测试AOP的配置*/@RunWith(value = SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:applicationContext.xml")public class AOPTest {@Autowiredprivate AccountService as;@Testpublic void proxy(){//3.执行方法as.saveAccount();as.updateAccount(1);as.deleteAccount();}}
切入点表达式的写法关键字:execution(表达式)表达式:参数一:访问修饰符(非必填)参数二:返回值(必填)参数三:包名.类名(非必填)参数四:方法名(参数)(必填)参数五:异常(非必填)访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)标准的表达式写法:public void com.it.service.impl.AccountServiceImpl.saveAccount()访问修饰符可以省略void com.it.service.impl.AccountServiceImpl.saveAccount()返回值可以使用通配符(*:表示任意),表示任意返回值* com.it.service.impl.AccountServiceImpl.saveAccount()包名可以使用通配符,表示任意包。但是有几级包,就需要写几个*.* *.*.*.*.AccountServiceImpl.saveAccount())包名可以使用..表示当前包及其子包* *..AccountServiceImpl.saveAccount()类名和方法名都可以使用*来实现通配(一般情况下,不会这样配置)* *..*.*() == * *()参数列表:可以直接写数据类型:基本类型直接写名称 int引用类型写包名.类名的方式 java.lang.String可以使用通配符表示任意类型,但是必须有参数可以使用..表示有无参数均可,有参数可以是任意类型全通配写法:* *..*.*(..)实际开发中切入点表达式的通常写法:切到业务层实现类下的所有方法:* com.it.service..*.*(..)
最终
<aop:before method="printLog" pointcut="execution(* com.it.service..*.*(..))"></aop:before>

坐标xml
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency></dependencies>
创建接口AccountService.java
/*** 账户的业务层接口*/public interface AccountService {/*** 模拟保存账户*/void saveAccount();/*** 模拟更新账户* @param i*/void updateAccount(int i);/*** 删除账户* @return*/int deleteAccount();}
创建接口的实现类AccountServiceImpl.java
/*** 账户的业务层实现类*/public class AccountServiceImpl implements AccountService {public void saveAccount() {System.out.println("执行了保存");}public void updateAccount(int i) {System.out.println("执行了更新"+i);}public int deleteAccount() {System.out.println("执行了删除");return 0;}}
创建增强类Logger.java
/*** 用于记录日志的工具类,它里面提供了公共的代码*/public class Logger {/*** 前置通知*/public void beforePrintLog(JoinPoint jp){System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");}/*** 后置通知*/public void afterReturningPrintLog(JoinPoint jp){System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");}/*** 异常通知*/public void afterThrowingPrintLog(JoinPoint jp){System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");}/*** 最终通知*/public void afterPrintLog(JoinPoint jp){System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");}/*** 环绕通知* 问题:* 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。* 分析:* 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。* 解决:* Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。** spring中的环绕通知:* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。*/public Object aroundPringLog(ProceedingJoinPoint pjp){Object rtValue = null;try{Object[] args = pjp.getArgs();//得到方法执行所需的参数System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");return rtValue;}catch (Throwable t){System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");throw new RuntimeException(t);}finally {System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");}}}
配置applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsd"><!-- 配置srping的Ioc,把service对象配置进来--><bean id="accountService" class="com.it.service.impl.AccountServiceImpl"></bean><!-- 配置Logger类 --><bean id="logger" class="com.it.utils.Logger"></bean><!--配置AOP--><aop:config><!-- 配置切入点表达式 id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容此标签写在aop:aspect标签内部只能当前切面使用。它还可以写在aop:aspect外面,此时就变成了所有切面可用--><aop:pointcut id="pt1" expression="execution(* com.it.service..*.*(..))"></aop:pointcut><!--配置切面 --><aop:aspect id="logAdvice" ref="logger"><!-- 配置前置通知:在切入点方法执行之前执行<aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>--><!-- 配置后置通知:在切入点方法正常执行之后值。它和异常通知永远只能执行一个<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>--><!-- 配置异常通知:在切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>--><!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>--><!-- 配置环绕通知 详细的注释请看Logger类中--><aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around></aop:aspect></aop:config></beans>
测试
/*** 测试AOP的配置*/@RunWith(value = SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:applicationContext.xml")public class AOPTest {@Autowiredprivate AccountService as;@Testpublic void proxy(){//3.执行方法as.saveAccount();}}
坐标xml
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.2.RELEASE</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.7</version></dependency></dependencies>
创建接口AccountService.java
/*** 账户的业务层接口*/public interface AccountService {/*** 模拟保存账户*/void saveAccount();/*** 模拟更新账户* @param i*/void updateAccount(int i);/*** 删除账户* @return*/int deleteAccount();}
创建接口的实现类AccountServiceImpl.java
/*** 账户的业务层实现类*/@Service("accountService")public class AccountServiceImpl implements AccountService {public void saveAccount() {System.out.println("执行了保存");//int i=1/0;}public void updateAccount(int i) {System.out.println("执行了更新"+i);}public int deleteAccount() {System.out.println("执行了删除");return 0;}}
创建增强类Logger.java
/*** 用于记录日志的工具类,它里面提供了公共的代码*/@Component("logger")@Aspect//表示当前类是一个切面类public class Logger {@Pointcut("execution(* com.it.service..*.*(..))")private void pt1(){}/*** 前置通知*/// @Before("pt1()")public void beforePrintLog(JoinPoint jp){System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");}/*** 后置通知*/// @AfterReturning("pt1()")public void afterReturningPrintLog(JoinPoint jp){System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");}/*** 异常通知*/// @AfterThrowing("pt1()")public void afterThrowingPrintLog(JoinPoint jp){System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");}/*** 最终通知*/// @After("pt1()")public void afterPrintLog(JoinPoint jp){System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");}/*** 环绕通知* 问题:* 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。* 分析:* 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。* 解决:* Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。** spring中的环绕通知:* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。*/@Around("pt1()")public Object aroundPringLog(ProceedingJoinPoint pjp){Object rtValue = null;try{Object[] args = pjp.getArgs();//得到方法执行所需的参数System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");return rtValue;}catch (Throwable t){System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");throw new RuntimeException(t);}finally {System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");}}}
配置applicationContext.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"><!-- 配置spring创建容器时要扫描的包--><context:component-scan base-package="com.it"></context:component-scan><!-- 配置spring开启注解AOP的支持 --><aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
测试
/*** 测试AOP的配置*/@RunWith(value = SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = "classpath:applicationContext.xml")public class AOPTest {@Autowiredprivate AccountService as;@Testpublic void proxy(){//3.执行方法as.saveAccount();}}
发现问题:注解开发spring的aop,默认是:最终通知放置到了后置通知/异常通知的前面。要想实现最终通知放置到后置通知/异常通知的后面,怎么办?
解决方案:只能使用环绕通知。

完全使用注解
创建类SpringConfiguration.java
@Configuration@ComponentScan(basePackages="com.it")@EnableAspectJAutoProxypublic class SpringConfiguration {}
测试类,AOPAnnoTest.java
/*** 测试AOP的配置*/@RunWith(value = SpringJUnit4ClassRunner.class)@ContextConfiguration(classes = SpringConfiguration.class)public class AOPAnnoTest {@Autowiredprivate AccountService as;@Testpublic void proxy(){//3.执行方法as.saveAccount();}}
原文:https://www.cnblogs.com/leccoo/p/11117662.html