spring_three


转账案例

坐标:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.0.2.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-test</artifactId>
  10. <version>5.0.2.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>commons-dbutils</groupId>
  14. <artifactId>commons-dbutils</artifactId>
  15. <version>1.4</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>mysql</groupId>
  19. <artifactId>mysql-connector-java</artifactId>
  20. <version>5.1.6</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>c3p0</groupId>
  24. <artifactId>c3p0</artifactId>
  25. <version>0.9.1.2</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>junit</groupId>
  29. <artifactId>junit</artifactId>
  30. <version>4.12</version>
  31. </dependency>
  32. </dependencies>

创建实体类daomain

  1. /**
  2. * 账户的实体类
  3. */
  4. public class Account implements Serializable {
  5. private Integer id;
  6. private String name;
  7. private Float money;
  8. }

创建接口AccountDao.java

  1. /**
  2. * 账户的持久层接口
  3. */
  4. public interface AccountDao {
  5. /**
  6. * 查询所有
  7. * @return
  8. */
  9. List<Account> findAllAccount();
  10. /**
  11. * 查询一个
  12. * @return
  13. */
  14. Account findAccountById(Integer accountId);
  15. /**
  16. * 保存
  17. * @param account
  18. */
  19. void saveAccount(Account account);
  20. /**
  21. * 更新
  22. * @param account
  23. */
  24. void updateAccount(Account account);
  25. /**
  26. * 删除
  27. * @param acccountId
  28. */
  29. void deleteAccount(Integer acccountId);
  30. /**
  31. * 根据名称查询账户
  32. * @param accountName
  33. * @return 如果有唯一的一个结果就返回,如果没有结果就返回null
  34. * 如果结果集超过一个就抛异常
  35. */
  36. Account findAccountByName(String accountName);
  37. }

创建实现类AccountDaoImpl.java

  1. /**
  2. * 账户的持久层实现类
  3. */
  4. public class AccountDaoImpl implements AccountDao {
  5. private QueryRunner runner;
  6. public List<Account> findAllAccount() {
  7. try{
  8. return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
  9. }catch (Exception e) {
  10. throw new RuntimeException(e);
  11. }
  12. }
  13. public Account findAccountById(Integer accountId) {
  14. try{
  15. return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
  16. }catch (Exception e) {
  17. throw new RuntimeException(e);
  18. }
  19. }
  20. public void saveAccount(Account account) {
  21. try{
  22. runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
  23. }catch (Exception e) {
  24. throw new RuntimeException(e);
  25. }
  26. }
  27. public void updateAccount(Account account) {
  28. try{
  29. runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
  30. }catch (Exception e) {
  31. throw new RuntimeException(e);
  32. }
  33. }
  34. public void deleteAccount(Integer accountId) {
  35. try{
  36. runner.update("delete from account where id=?",accountId);
  37. }catch (Exception e) {
  38. throw new RuntimeException(e);
  39. }
  40. }
  41. public Account findAccountByName(String accountName) {
  42. try{
  43. List<Account> accounts = runner.query("select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);
  44. if(accounts == null || accounts.size() == 0){
  45. return null;
  46. }
  47. if(accounts.size() > 1){
  48. throw new RuntimeException("结果集不唯一,数据有问题");
  49. }
  50. return accounts.get(0);
  51. }catch (Exception e) {
  52. throw new RuntimeException(e);
  53. }
  54. }
  55. }

建接口AccountService.java

  1. /**
  2. * 账户的业务层接口
  3. */
  4. public interface AccountService {
  5. /**
  6. * 查询所有
  7. * @return
  8. */
  9. List<Account> findAllAccount();
  10. /**
  11. * 查询一个
  12. * @return
  13. */
  14. Account findAccountById(Integer accountId);
  15. /**
  16. * 保存
  17. * @param account
  18. */
  19. void saveAccount(Account account);
  20. /**
  21. * 更新
  22. * @param account
  23. */
  24. void updateAccount(Account account);
  25. /**
  26. * 删除
  27. * @param acccountId
  28. */
  29. void deleteAccount(Integer acccountId);
  30. /**
  31. * 转账
  32. * @param sourceName 转出账户名称
  33. * @param targetName 转入账户名称
  34. * @param money 转账金额
  35. */
  36. void transfer(String sourceName, String targetName, Float money);
  37. }

创建接口的实现类,AccountServiceImpl.java

  1. /**
  2. * 账户的业务层实现类
  3. *
  4. * 事务控制应该都是在业务层
  5. */
  6. public class AccountServiceImpl implements AccountService {
  7. private AccountDao accountDao;
  8. public void setAccountDao(AccountDao accountDao) {
  9. this.accountDao = accountDao;
  10. }
  11. public List<Account> findAllAccount() {
  12. return accountDao.findAllAccount();
  13. }
  14. public Account findAccountById(Integer accountId) {
  15. return accountDao.findAccountById(accountId);
  16. }
  17. public void saveAccount(Account account) {
  18. accountDao.saveAccount(account);
  19. }
  20. public void updateAccount(Account account) {
  21. accountDao.updateAccount(account);
  22. }
  23. public void deleteAccount(Integer acccountId) {
  24. accountDao.deleteAccount(acccountId);
  25. }
  26. public void transfer(String sourceName, String targetName, Float money) {
  27. System.out.println("transfer....");
  28. //2.1根据名称查询转出账户
  29. Account source = accountDao.findAccountByName(sourceName);
  30. //2.2根据名称查询转入账户
  31. Account target = accountDao.findAccountByName(targetName);
  32. //2.3转出账户减钱
  33. source.setMoney(source.getMoney()-money);
  34. //2.4转入账户加钱
  35. target.setMoney(target.getMoney()+money);
  36. //2.5更新转出账户
  37. accountDao.updateAccount(source);
  38. int i=1/0;
  39. //2.6更新转入账户
  40. accountDao.updateAccount(target);
  41. }
  42. }

配置applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- 配置Service -->
  7. <bean id="accountService" class="com.it.service.impl.AccountServiceImpl">
  8. <!-- 注入dao -->
  9. <property name="accountDao" ref="accountDao"></property>
  10. </bean>
  11. <!--配置Dao对象-->
  12. <bean id="accountDao" class="com.it.dao.impl.AccountDaoImpl">
  13. <!-- 注入QueryRunner -->
  14. <property name="runner" ref="runner"></property>
  15. </bean>
  16. <!--配置QueryRunner-->
  17. <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
  18. <constructor-arg name="ds" ref="dataSource"></constructor-arg>
  19. </bean>
  20. <!-- 配置数据源 -->
  21. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  22. <!--连接数据库的必备信息-->
  23. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  24. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/itcastspring"></property>
  25. <property name="user" value="root"></property>
  26. <property name="password" value="root"></property>
  27. </bean>
  28. </beans>

测试AccountServiceTest.java

  1. /**
  2. * 使用Junit单元测试:测试我们的配置
  3. */
  4. @RunWith(SpringJUnit4ClassRunner.class)
  5. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  6. public class AccountServiceTest {
  7. @Autowired
  8. private AccountService as;
  9. @Test
  10. public void testTransfer(){
  11. as.transfer("aaa","bbb",100f);
  12. }
  13. }

事务被自动控制了。换言之,我们使用了connection对象的setAutoCommit(true)


添加事务

1561994325830

如果在AccountServiceImpl.java中的transfer方法中,抛出一个异常。此时事务不会回滚,原因是DBUtils每个操作数据都是获取一个连接,每个连接的事务都是独立的,且默认是自动提交。

解决方案:

需要使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只能有一个能控制事务的连接对象。

ConnectionUtils.java

  1. /**
  2. * 连接的工具类,它用于从数据源中获取一个连接,并且实现和线程的绑定
  3. */
  4. public class ConnectionUtils {
  5. private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
  6. //注入数据源
  7. private DataSource dataSource;
  8. public void setDataSource(DataSource dataSource) {
  9. this.dataSource = dataSource;
  10. }
  11. /**
  12. * 获取当前线程上的连接,
  13. * @return
  14. */
  15. public Connection getThreadConnection() {
  16. try{
  17. //1.先从ThreadLocal上获取
  18. Connection conn = tl.get();
  19. //2.判断当前线程上是否有连接
  20. if (conn == null) {
  21. //3.从数据源中获取一个连接,并且存入ThreadLocal中
  22. conn = dataSource.getConnection();
  23. tl.set(conn);
  24. }
  25. //4.返回当前线程上的连接
  26. return conn;
  27. }catch (Exception e){
  28. throw new RuntimeException(e);
  29. }
  30. }
  31. /**
  32. * 把连接和线程解绑(在当前线程结束的时候执行)
  33. */
  34. public void removeConnection(){
  35. tl.remove();
  36. }
  37. }

TransactionManager.java

和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接

  1. /**
  2. * 和事务管理相关的工具类,它包含了,开启事务,提交事务,回滚事务和释放连接
  3. */
  4. public class TransactionManager {
  5. private ConnectionUtils connectionUtils;
  6. public void setConnectionUtils(ConnectionUtils connectionUtils) {
  7. this.connectionUtils = connectionUtils;
  8. }
  9. /**
  10. * 开启事务
  11. */
  12. public void beginTransaction(){
  13. try {
  14. connectionUtils.getThreadConnection().setAutoCommit(false);
  15. }catch (Exception e){
  16. e.printStackTrace();
  17. }
  18. }
  19. /**
  20. * 提交事务
  21. */
  22. public void commit(){
  23. try {
  24. connectionUtils.getThreadConnection().commit();
  25. }catch (Exception e){
  26. e.printStackTrace();
  27. }
  28. }
  29. /**
  30. * 回滚事务
  31. */
  32. public void rollback(){
  33. try {
  34. connectionUtils.getThreadConnection().rollback();
  35. }catch (Exception e){
  36. e.printStackTrace();
  37. }
  38. }
  39. /**
  40. * 释放连接
  41. */
  42. public void release(){
  43. try {
  44. connectionUtils.getThreadConnection().close();//把连接还回连接池中
  45. connectionUtils.removeConnection();//线程和连接解绑
  46. }catch (Exception e){
  47. e.printStackTrace();
  48. }
  49. }
  50. }

配置AccountDaoImpl.java

注入连接工具对象,使得操作数据库从同一个连接中获取

  1. /**
  2. * 账户的持久层实现类
  3. */
  4. public class AccountDaoImpl implements AccountDao {
  5. private QueryRunner runner;
  6. private ConnectionUtils connectionUtils;
  7. public void setConnectionUtils(ConnectionUtils connectionUtils) {
  8. this.connectionUtils = connectionUtils;
  9. }
  10. public void setRunner(QueryRunner runner) {
  11. this.runner = runner;
  12. }
  13. public List<Account> findAllAccount() {
  14. try{
  15. return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
  16. }catch (Exception e) {
  17. throw new RuntimeException(e);
  18. }
  19. }
  20. public Account findAccountById(Integer accountId) {
  21. try{
  22. return runner.query(connectionUtils.getThreadConnection(),"select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
  23. }catch (Exception e) {
  24. throw new RuntimeException(e);
  25. }
  26. }
  27. public void saveAccount(Account account) {
  28. try{
  29. runner.update(connectionUtils.getThreadConnection(),"insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
  30. }catch (Exception e) {
  31. throw new RuntimeException(e);
  32. }
  33. }
  34. public void updateAccount(Account account) {
  35. try{
  36. runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
  37. }catch (Exception e) {
  38. throw new RuntimeException(e);
  39. }
  40. }
  41. public void deleteAccount(Integer accountId) {
  42. try{
  43. runner.update(connectionUtils.getThreadConnection(),"delete from account where id=?",accountId);
  44. }catch (Exception e) {
  45. throw new RuntimeException(e);
  46. }
  47. }
  48. public Account findAccountByName(String accountName) {
  49. try{
  50. List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);
  51. if(accounts == null || accounts.size() == 0){
  52. return null;
  53. }
  54. if(accounts.size() > 1){
  55. throw new RuntimeException("结果集不唯一,数据有问题");
  56. }
  57. return accounts.get(0);
  58. }catch (Exception e) {
  59. throw new RuntimeException(e);
  60. }
  61. }
  62. }

配置AccountServiceImpl.java

事务操作一定需要在Service层控制。

作用:注入事务管理器对象,对每个操作都需要开启事务、提交事务、关闭事务,如果抛出异常,需要回滚事务。

  1. /**
  2. * 账户的业务层实现类
  3. *
  4. * 事务控制应该都是在业务层
  5. */
  6. public class AccountServiceImpl implements AccountService {
  7. private AccountDao accountDao;
  8. private TransactionManager txManager;
  9. public void setTxManager(TransactionManager txManager) {
  10. this.txManager = txManager;
  11. }
  12. public void setAccountDao(AccountDao accountDao) {
  13. this.accountDao = accountDao;
  14. }
  15. public List<Account> findAllAccount() {
  16. try {
  17. //1.开启事务
  18. txManager.beginTransaction();
  19. //2.执行操作
  20. List<Account> accounts = accountDao.findAllAccount();
  21. //3.提交事务
  22. txManager.commit();
  23. //4.返回结果
  24. return accounts;
  25. }catch (Exception e){
  26. //5.回滚操作
  27. txManager.rollback();
  28. throw new RuntimeException(e);
  29. }finally {
  30. //6.释放连接
  31. txManager.release();
  32. }
  33. }
  34. public Account findAccountById(Integer accountId) {
  35. try {
  36. //1.开启事务
  37. txManager.beginTransaction();
  38. //2.执行操作
  39. Account account = accountDao.findAccountById(accountId);
  40. //3.提交事务
  41. txManager.commit();
  42. //4.返回结果
  43. return account;
  44. }catch (Exception e){
  45. //5.回滚操作
  46. txManager.rollback();
  47. throw new RuntimeException(e);
  48. }finally {
  49. //6.释放连接
  50. txManager.release();
  51. }
  52. }
  53. public void saveAccount(Account account) {
  54. try {
  55. //1.开启事务
  56. txManager.beginTransaction();
  57. //2.执行操作
  58. accountDao.saveAccount(account);
  59. //3.提交事务
  60. txManager.commit();
  61. }catch (Exception e){
  62. //4.回滚操作
  63. txManager.rollback();
  64. }finally {
  65. //5.释放连接
  66. txManager.release();
  67. }
  68. }
  69. public void updateAccount(Account account) {
  70. try {
  71. //1.开启事务
  72. txManager.beginTransaction();
  73. //2.执行操作
  74. accountDao.updateAccount(account);
  75. //3.提交事务
  76. txManager.commit();
  77. }catch (Exception e){
  78. //4.回滚操作
  79. txManager.rollback();
  80. }finally {
  81. //5.释放连接
  82. txManager.release();
  83. }
  84. }
  85. public void deleteAccount(Integer acccountId) {
  86. try {
  87. //1.开启事务
  88. txManager.beginTransaction();
  89. //2.执行操作
  90. accountDao.deleteAccount(acccountId);
  91. //3.提交事务
  92. txManager.commit();
  93. }catch (Exception e){
  94. //4.回滚操作
  95. txManager.rollback();
  96. }finally {
  97. //5.释放连接
  98. txManager.release();
  99. }
  100. }
  101. public void transfer(String sourceName, String targetName, Float money) {
  102. try {
  103. //1.开启事务
  104. txManager.beginTransaction();
  105. //2.执行操作
  106. //2.1根据名称查询转出账户
  107. Account source = accountDao.findAccountByName(sourceName);
  108. //2.2根据名称查询转入账户
  109. Account target = accountDao.findAccountByName(targetName);
  110. //2.3转出账户减钱
  111. source.setMoney(source.getMoney()-money);
  112. //2.4转入账户加钱
  113. target.setMoney(target.getMoney()+money);
  114. //2.5更新转出账户
  115. accountDao.updateAccount(source);
  116. int i=1/0;
  117. //2.6更新转入账户
  118. accountDao.updateAccount(target);
  119. //3.提交事务
  120. txManager.commit();
  121. }catch (Exception e){
  122. //4.回滚操作
  123. txManager.rollback();
  124. e.printStackTrace();
  125. }finally {
  126. //5.释放连接
  127. txManager.release();
  128. }
  129. }
  130. }

配置applicationContext.xml

  1. <!-- 配置Service -->
  2. <bean id="accountService" class="com.it.service.impl.AccountServiceImpl">
  3. <!-- 注入dao -->
  4. <property name="accountDao" ref="accountDao"></property>
  5. <!--注入事务管理器-->
  6. <property name="txManager" ref="txManager"></property>
  7. </bean>
  8. <!--配置Dao对象-->
  9. <bean id="accountDao" class="com.it.dao.impl.AccountDaoImpl">
  10. <!-- 注入QueryRunner -->
  11. <property name="runner" ref="runner"></property>
  12. <!-- 注入ConnectionUtils -->
  13. <property name="connectionUtils" ref="connectionUtils"></property>
  14. </bean>
  15. <!--配置QueryRunner-->
  16. <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
  17. <!--这里要去掉queryRunner的默认连接池配置,由ConnectionUtils 获取连接-->
  18. <!--<constructor-arg name="ds" ref="dataSource"></constructor-arg>-->
  19. </bean>
  20. <!-- 配置数据源 -->
  21. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  22. <!--连接数据库的必备信息-->
  23. <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
  24. <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/itcastspring"></property>
  25. <property name="user" value="root"></property>
  26. <property name="password" value="root"></property>
  27. </bean>
  28. <!-- 配置Connection的工具类 ConnectionUtils -->
  29. <bean id="connectionUtils" class="com.it.utils.ConnectionUtils">
  30. <!-- 注入数据源-->
  31. <property name="dataSource" ref="dataSource"></property>
  32. </bean>
  33. <!-- 配置事务管理器-->
  34. <bean id="txManager" class="com.it.utils.TransactionManager">
  35. <!-- 注入ConnectionUtils -->
  36. <property name="connectionUtils" ref="connectionUtils"></property>
  37. </bean>

通过对业务层改造,已经可以实现事务控制了,但是由于我们添加了事务控制,也产生了一个新的问题: 
业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了。 
试想一下,如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层实现类可能有十几个甚至几十个。

【思考】: 
这个问题能不能解决呢? 
答案是肯定的,使用下一小节中提到的技术


AOP

AOP的概述

1561994683230

AOP (Aspect Oriented Programing) 称为:面向切面编程,它是一种编程思想。 
AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码的编写方式(应用场景:例如性能监视、事务管理、安全检查、缓存、日志记录等)。

【扩展了解】AOP 是 OOP(面向对象编程(Object Oriented Programming,OOP,面向对象程序设计)是一种计算机编程架构),思想延续 !

1561994739908


AOP的作用

  • 权限校验
  • 日志记录
  • 性能检测
  • 缓存技术
  • 事务管理

AOP底层实现

代理机制。

2个:spring的aop的底层原理

1:JDK代理(要求目标对象面向接口)(spring默认的代理方式是JDK代理)

2:CGLIB代理(面向接口、面向类)


AOP相关术语

Joinpoint(连接点): (方法)

所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。

Pointcut(切入点): (方法)

所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。

Advice(通知/增强): (方法)

所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。 
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。

Aspect(切面): (类)

是切入点和通知(引介)的结合。

  • Target(目标对象): 代理的目标对象。
  • Weaving(织入): (了解)是指把增强应用到目标对象来创建新的代理对象的过程。 
    spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
  • Proxy(代理): 一个类被AOP织入增强后,就产生一个结果代理类。

1561995019185


Spring的AOP配置(添加日志)

坐标xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.0.2.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-test</artifactId>
  10. <version>5.0.2.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>junit</groupId>
  14. <artifactId>junit</artifactId>
  15. <version>4.12</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.aspectj</groupId>
  19. <artifactId>aspectjweaver</artifactId>
  20. <version>1.8.7</version>
  21. </dependency>

定义Service的接口和实现类,创建接口AccountService.java

  1. **
  2. * 账户的业务层接口
  3. */
  4. public interface AccountService {
  5. /**
  6. * 模拟保存账户
  7. */
  8. void saveAccount();
  9. /**
  10. * 模拟更新账户
  11. * @param i
  12. */
  13. void updateAccount(int i);
  14. /**
  15. * 删除账户
  16. * @return
  17. */
  18. int deleteAccount();
  19. }

创建接口的实现类AccountServiceImpl.java

  1. **
  2. * 账户的业务层实现类
  3. */
  4. public class AccountServiceImpl implements AccountService {
  5. public void saveAccount() {
  6. System.out.println("执行了保存");
  7. }
  8. public void updateAccount(int i) {
  9. System.out.println("执行了更新"+i);
  10. }
  11. public int deleteAccount() {
  12. System.out.println("执行了删除");
  13. return 0;
  14. }
  15. }

创建增强类Logger.java

  1. /**
  2. * 用于记录日志的工具类,它里面提供了公共的代码
  3. */
  4. public class Logger {
  5. /**
  6. * 用于打印日志:计划让其在切入点方法执行之前执行(切入点方法就是业务层方法)
  7. */
  8. public void printLog(){
  9. System.out.println("Logger类中的pringLog方法开始记录日志了。。。");
  10. }
  11. }

配置applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop.xsd">
  9. <!-- 配置srping的Ioc,把service对象配置进来-->
  10. <bean id="accountService" class="com.it.service.impl.AccountServiceImpl"></bean>
  11. <!--spring中基于XML的AOP配置步骤
  12. 1、把通知Bean也交给spring来管理
  13. 2、使用aop:config标签表明开始AOP的配置
  14. 3、使用aop:aspect标签表明配置切面
  15. id属性:是给切面提供一个唯一标识
  16. ref属性:是指定通知类bean的Id。
  17. 4、在aop:aspect标签的内部使用对应标签来配置通知的类型
  18. 我们现在示例是让printLog方法在切入点方法执行之前执行:所以是前置通知
  19. aop:before:表示配置前置通知
  20. method属性:用于指定Logger类中哪个方法是前置通知
  21. pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
  22. 切入点表达式的写法:
  23. 关键字:execution(表达式)
  24. -->
  25. <!-- 配置Logger类,声明切面(创建对象,不是真正aop的切面) -->
  26. <bean id="logger" class="com.it.utils.Logger"></bean>
  27. <!--配置AOP-->
  28. <aop:config>
  29. <!--配置切面 -->
  30. <aop:aspect id="logAdvice" ref="logger">
  31. <!-- 配置通知的类型,并且建立通知方法和切入点方法的关联-->
  32. <aop:before method="printLog" pointcut="execution(void com.it.service.impl.AccountServiceImpl.saveAccount())"></aop:before>
  33. <aop:before method="printLog" pointcut="execution(void com.it.service.impl.AccountServiceImpl.updateAccount(int))"></aop:before>
  34. <aop:before method="printLog" pointcut="execution(int com.it.service.impl.AccountServiceImpl.deleteAccount())"></aop:before>
  35. </aop:aspect>
  36. </aop:config>
  37. </beans>

1561995224189

测试

  1. /**
  2. * 测试AOP的配置
  3. */
  4. @RunWith(value = SpringJUnit4ClassRunner.class)
  5. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  6. public class AOPTest {
  7. @Autowired
  8. private AccountService as;
  9. @Test
  10. public void proxy(){
  11. //3.执行方法
  12. as.saveAccount();
  13. as.updateAccount(1);
  14. as.deleteAccount();
  15. }
  16. }

切入点表达式的写法(重点)

  1. 切入点表达式的写法
  2. 关键字:execution(表达式)
  3. 表达式:
  4. 参数一:访问修饰符(非必填)
  5. 参数二:返回值(必填)
  6. 参数三:包名.类名(非必填)
  7. 参数四:方法名(参数)(必填)
  8. 参数五:异常(非必填)
  9. 访问修饰符 返回值 包名.包名.包名...类名.方法名(参数列表)
  10. 标准的表达式写法:
  11. public void com.it.service.impl.AccountServiceImpl.saveAccount()
  12. 访问修饰符可以省略
  13. void com.it.service.impl.AccountServiceImpl.saveAccount()
  14. 返回值可以使用通配符(*:表示任意),表示任意返回值
  15. * com.it.service.impl.AccountServiceImpl.saveAccount()
  16. 包名可以使用通配符,表示任意包。但是有几级包,就需要写几个*.
  17. * *.*.*.*.AccountServiceImpl.saveAccount())
  18. 包名可以使用..表示当前包及其子包
  19. * *..AccountServiceImpl.saveAccount()
  20. 类名和方法名都可以使用*来实现通配(一般情况下,不会这样配置)
  21. * *..*.*() == * *()
  22. 参数列表:
  23. 可以直接写数据类型:
  24. 基本类型直接写名称 int
  25. 引用类型写包名.类名的方式 java.lang.String
  26. 可以使用通配符表示任意类型,但是必须有参数
  27. 可以使用..表示有无参数均可,有参数可以是任意类型
  28. 全通配写法:* *..*.*(..)
  29. 实际开发中切入点表达式的通常写法:切到业务层实现类下的所有方法:* com.it.service..*.*(..)

最终

  1. <aop:before method="printLog" pointcut="execution(* com.it.service..*.*(..))">
  2. </aop:before>

Spring AOP的五种通知类型(使用XML)

  • 前置通知
  • 后置通知
  • 异常通知
  • 最终通知
  • 环绕通知

1561995468818

坐标xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.0.2.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-test</artifactId>
  10. <version>5.0.2.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>junit</groupId>
  14. <artifactId>junit</artifactId>
  15. <version>4.12</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.aspectj</groupId>
  19. <artifactId>aspectjweaver</artifactId>
  20. <version>1.8.7</version>
  21. </dependency>
  22. </dependencies>

创建接口AccountService.java

  1. /**
  2. * 账户的业务层接口
  3. */
  4. public interface AccountService {
  5. /**
  6. * 模拟保存账户
  7. */
  8. void saveAccount();
  9. /**
  10. * 模拟更新账户
  11. * @param i
  12. */
  13. void updateAccount(int i);
  14. /**
  15. * 删除账户
  16. * @return
  17. */
  18. int deleteAccount();
  19. }

创建接口的实现类AccountServiceImpl.java

  1. /**
  2. * 账户的业务层实现类
  3. */
  4. public class AccountServiceImpl implements AccountService {
  5. public void saveAccount() {
  6. System.out.println("执行了保存");
  7. }
  8. public void updateAccount(int i) {
  9. System.out.println("执行了更新"+i);
  10. }
  11. public int deleteAccount() {
  12. System.out.println("执行了删除");
  13. return 0;
  14. }
  15. }

创建增强类Logger.java

  1. /**
  2. * 用于记录日志的工具类,它里面提供了公共的代码
  3. */
  4. public class Logger {
  5. /**
  6. * 前置通知
  7. */
  8. public void beforePrintLog(JoinPoint jp){
  9. System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
  10. }
  11. /**
  12. * 后置通知
  13. */
  14. public void afterReturningPrintLog(JoinPoint jp){
  15. System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");
  16. }
  17. /**
  18. * 异常通知
  19. */
  20. public void afterThrowingPrintLog(JoinPoint jp){
  21. System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");
  22. }
  23. /**
  24. * 最终通知
  25. */
  26. public void afterPrintLog(JoinPoint jp){
  27. System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");
  28. }
  29. /**
  30. * 环绕通知
  31. * 问题:
  32. * 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
  33. * 分析:
  34. * 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
  35. * 解决:
  36. * Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
  37. * 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
  38. *
  39. * spring中的环绕通知:
  40. * 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
  41. */
  42. public Object aroundPringLog(ProceedingJoinPoint pjp){
  43. Object rtValue = null;
  44. try{
  45. Object[] args = pjp.getArgs();//得到方法执行所需的参数
  46. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");
  47. rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
  48. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");
  49. return rtValue;
  50. }catch (Throwable t){
  51. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
  52. throw new RuntimeException(t);
  53. }finally {
  54. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
  55. }
  56. }
  57. }

配置applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/aop
  8. http://www.springframework.org/schema/aop/spring-aop.xsd">
  9. <!-- 配置srping的Ioc,把service对象配置进来-->
  10. <bean id="accountService" class="com.it.service.impl.AccountServiceImpl"></bean>
  11. <!-- 配置Logger类 -->
  12. <bean id="logger" class="com.it.utils.Logger"></bean>
  13. <!--配置AOP-->
  14. <aop:config>
  15. <!-- 配置切入点表达式 id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容
  16. 此标签写在aop:aspect标签内部只能当前切面使用。
  17. 它还可以写在aop:aspect外面,此时就变成了所有切面可用
  18. -->
  19. <aop:pointcut id="pt1" expression="execution(* com.it.service..*.*(..))"></aop:pointcut>
  20. <!--配置切面 -->
  21. <aop:aspect id="logAdvice" ref="logger">
  22. <!-- 配置前置通知:在切入点方法执行之前执行
  23. <aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>-->
  24. <!-- 配置后置通知:在切入点方法正常执行之后值。它和异常通知永远只能执行一个
  25. <aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>-->
  26. <!-- 配置异常通知:在切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个
  27. <aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>-->
  28. <!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行
  29. <aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>-->
  30. <!-- 配置环绕通知 详细的注释请看Logger类中-->
  31. <aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around>
  32. </aop:aspect>
  33. </aop:config>
  34. </beans>

测试

  1. /**
  2. * 测试AOP的配置
  3. */
  4. @RunWith(value = SpringJUnit4ClassRunner.class)
  5. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  6. public class AOPTest {
  7. @Autowired
  8. private AccountService as;
  9. @Test
  10. public void proxy(){
  11. //3.执行方法
  12. as.saveAccount();
  13. }
  14. }

Spring AOP的注解方式配置五种通知类型

坐标xml

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.0.2.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-test</artifactId>
  10. <version>5.0.2.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>junit</groupId>
  14. <artifactId>junit</artifactId>
  15. <version>4.12</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.aspectj</groupId>
  19. <artifactId>aspectjweaver</artifactId>
  20. <version>1.8.7</version>
  21. </dependency>
  22. </dependencies>

创建接口AccountService.java

  1. /**
  2. * 账户的业务层接口
  3. */
  4. public interface AccountService {
  5. /**
  6. * 模拟保存账户
  7. */
  8. void saveAccount();
  9. /**
  10. * 模拟更新账户
  11. * @param i
  12. */
  13. void updateAccount(int i);
  14. /**
  15. * 删除账户
  16. * @return
  17. */
  18. int deleteAccount();
  19. }

创建接口的实现类AccountServiceImpl.java

  1. /**
  2. * 账户的业务层实现类
  3. */
  4. @Service("accountService")
  5. public class AccountServiceImpl implements AccountService {
  6. public void saveAccount() {
  7. System.out.println("执行了保存");
  8. //int i=1/0;
  9. }
  10. public void updateAccount(int i) {
  11. System.out.println("执行了更新"+i);
  12. }
  13. public int deleteAccount() {
  14. System.out.println("执行了删除");
  15. return 0;
  16. }
  17. }

创建增强类Logger.java

  1. /**
  2. * 用于记录日志的工具类,它里面提供了公共的代码
  3. */
  4. @Component("logger")
  5. @Aspect//表示当前类是一个切面类
  6. public class Logger {
  7. @Pointcut("execution(* com.it.service..*.*(..))")
  8. private void pt1(){}
  9. /**
  10. * 前置通知
  11. */
  12. // @Before("pt1()")
  13. public void beforePrintLog(JoinPoint jp){
  14. System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
  15. }
  16. /**
  17. * 后置通知
  18. */
  19. // @AfterReturning("pt1()")
  20. public void afterReturningPrintLog(JoinPoint jp){
  21. System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");
  22. }
  23. /**
  24. * 异常通知
  25. */
  26. // @AfterThrowing("pt1()")
  27. public void afterThrowingPrintLog(JoinPoint jp){
  28. System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");
  29. }
  30. /**
  31. * 最终通知
  32. */
  33. // @After("pt1()")
  34. public void afterPrintLog(JoinPoint jp){
  35. System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");
  36. }
  37. /**
  38. * 环绕通知
  39. * 问题:
  40. * 当我们配置了环绕通知之后,切入点方法没有执行,而通知方法执行了。
  41. * 分析:
  42. * 通过对比动态代理中的环绕通知代码,发现动态代理的环绕通知有明确的切入点方法调用,而我们的代码中没有。
  43. * 解决:
  44. * Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
  45. * 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
  46. *
  47. * spring中的环绕通知:
  48. * 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
  49. */
  50. @Around("pt1()")
  51. public Object aroundPringLog(ProceedingJoinPoint pjp){
  52. Object rtValue = null;
  53. try{
  54. Object[] args = pjp.getArgs();//得到方法执行所需的参数
  55. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");
  56. rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
  57. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");
  58. return rtValue;
  59. }catch (Throwable t){
  60. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
  61. throw new RuntimeException(t);
  62. }finally {
  63. System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
  64. }
  65. }
  66. }

配置applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:context="http://www.springframework.org/schema/context"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/aop
  9. http://www.springframework.org/schema/aop/spring-aop.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd">
  12. <!-- 配置spring创建容器时要扫描的包-->
  13. <context:component-scan base-package="com.it"></context:component-scan>
  14. <!-- 配置spring开启注解AOP的支持 -->
  15. <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  16. </beans>

测试

  1. /**
  2. * 测试AOP的配置
  3. */
  4. @RunWith(value = SpringJUnit4ClassRunner.class)
  5. @ContextConfiguration(locations = "classpath:applicationContext.xml")
  6. public class AOPTest {
  7. @Autowired
  8. private AccountService as;
  9. @Test
  10. public void proxy(){
  11. //3.执行方法
  12. as.saveAccount();
  13. }
  14. }

发现问题:注解开发spring的aop,默认是:最终通知放置到了后置通知/异常通知的前面。要想实现最终通知放置到后置通知/异常通知的后面,怎么办?

解决方案:只能使用环绕通知

1561995820024


完全使用注解

创建类SpringConfiguration.java

  1. @Configuration
  2. @ComponentScan(basePackages="com.it")
  3. @EnableAspectJAutoProxy
  4. public class SpringConfiguration {
  5. }

测试类,AOPAnnoTest.java

  1. /**
  2. * 测试AOP的配置
  3. */
  4. @RunWith(value = SpringJUnit4ClassRunner.class)
  5. @ContextConfiguration(classes = SpringConfiguration.class)
  6. public class AOPAnnoTest {
  7. @Autowired
  8. private AccountService as;
  9. @Test
  10. public void proxy(){
  11. //3.执行方法
  12. as.saveAccount();
  13. }
  14. }
posted @ 2019-07-01 23:54  不穿格子衫的徍爺  阅读(161)  评论(0编辑  收藏  举报