第一章:设计模式—代理模式

1.1 概述

  • 代理模式:给某一个对象提供一个代理对象,并由代理对象控制对源对象的引用。代理就是一个人或一个机构代表另一个人或者一个机构采取行动。某些情况下,客户不想或者不能够直接引用一个对象,代理对象可以在客户和目标对象中间起到中介的作用。客户端分辨不出代理主题对象和真实主题对象的区别。代理模式可以并不知道被代理对象,而仅仅持有一个被代理对象的接口,这时代理对象不能够创建被代理对象,被代理对象必须有系统的其他角色代为创建并传入。
  • 为什么需要代理模式?
    • ① 它有间接的特点,可以起到中介隔离作用。就好比在租房的时候,房东可能不在本地,而短期内又不能赶回来,此时中介的出场,就作为房东的代理实现和我们签订承租合同。而我们和房东之间就没有耦合了。
    • ② 它有增强的功能。还以租房为例,我们首先考虑的是找一个靠谱的中介,由中介给我们提供房源信息,并且告诉我们房屋的细节、合同的细节等等。当然我们也可以自己去找一些个人出租的房屋,但是在这之中,我们要了解租赁合同,房屋验收、租金监管等情况,这无疑对我们是繁重的工作。而有了中介作为我们的代理中间人,他把了解到的信息告诉我们,我们一样可以租到房子,而不必做哪些繁重的工作。

1.2 应用示例

1.2.1 准备工作

  • sql脚本:
  1. DROP TABLE IF EXISTS `account`;
  2. CREATE TABLE `account` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  5. `money` double NULL DEFAULT NULL,
  6. PRIMARY KEY (`id`) USING BTREE
  7. ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  8. INSERT INTO `account` VALUES (1, '张三', 1000);
  9. INSERT INTO `account` VALUES (2, '李四', 1000);
  • 导入相关jar包的Maven坐标:
  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-context</artifactId>
  4. <version>5.2.7.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework</groupId>
  8. <artifactId>spring-web</artifactId>
  9. <version>5.2.7.RELEASE</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework</groupId>
  13. <artifactId>spring-webmvc</artifactId>
  14. <version>5.2.7.RELEASE</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework</groupId>
  18. <artifactId>spring-aspects</artifactId>
  19. <version>5.2.7.RELEASE</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>com.alibaba</groupId>
  23. <artifactId>druid</artifactId>
  24. <version>1.1.23</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.springframework</groupId>
  28. <artifactId>spring-jdbc</artifactId>
  29. <version>5.2.7.RELEASE</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework</groupId>
  33. <artifactId>spring-test</artifactId>
  34. <version>5.2.7.RELEASE</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>mysql</groupId>
  38. <artifactId>mysql-connector-java</artifactId>
  39. <version>8.0.19</version>
  40. </dependency>
  41. <!-- 导入YAML解析工厂坐标 -->
  42. <dependency>
  43. <groupId>org.yaml</groupId>
  44. <artifactId>snakeyaml</artifactId>
  45. <version>1.26</version>
  46. </dependency>
  47. <dependency>
  48. <groupId>junit</groupId>
  49. <artifactId>junit</artifactId>
  50. <version>4.13</version>
  51. <scope>test</scope>
  52. </dependency>
  53. <dependency>
  54. <groupId>javax.inject</groupId>
  55. <artifactId>javax.inject</artifactId>
  56. <version>1</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>javax.annotation</groupId>
  60. <artifactId>javax.annotation-api</artifactId>
  61. <version>1.3.2</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>javax.servlet</groupId>
  65. <artifactId>javax.servlet-api</artifactId>
  66. <version>4.0.1</version>
  67. </dependency>
  • 日志文件log4j2.xml
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
  3. <!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,可以看到log4j2内部各种详细输出-->
  4. <configuration status="INFO">
  5. <!--先定义所有的appender-->
  6. <appenders>
  7. <!--输出日志信息到控制台-->
  8. <console name="Console" target="SYSTEM_OUT">
  9. <!--控制日志输出的格式-->
  10. <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
  11. </console>
  12. </appenders>
  13. <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
  14. <!--root:用于指定项目的根日志,如果没有单独指定Logger,则会使用root作为默认的日志输出-->
  15. <loggers>
  16. <root level="info">
  17. <appender-ref ref="Console"/>
  18. </root>
  19. </loggers>
  20. </configuration>
  • jdbc.yml
  1. # Yet Another Markup Language 另一种标记语言
  2. jdbc:
  3. url: jdbc:mysql://192.168.2.112:3306/spring5?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true&nullCatalogMeansCurrent=true
  4. driver: com.mysql.cj.jdbc.Driver
  5. user: root
  6. password: 123456
  • 自定义YAML的PropertySourceFactory
  1. package com.sunxiaping.spring5.factory;
  2. import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
  3. import org.springframework.core.env.PropertiesPropertySource;
  4. import org.springframework.core.env.PropertySource;
  5. import org.springframework.core.io.support.EncodedResource;
  6. import org.springframework.core.io.support.PropertySourceFactory;
  7. import java.io.IOException;
  8. import java.util.Properties;
  9. /**
  10. * 自定义YAML的PropertySourceFactory
  11. */
  12. public class YAMLPropertySourceFactory implements PropertySourceFactory {
  13. /**
  14. * 返回PropertySource对象
  15. *
  16. * @param name
  17. * @param resource
  18. * @return
  19. * @throws IOException
  20. */
  21. @Override
  22. public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
  23. //创建YAML文件解析工厂
  24. YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
  25. //设置要解析的资源内容
  26. factoryBean.setResources(resource.getResource());
  27. //把资源解析为properties文件
  28. Properties properties = factoryBean.getObject();
  29. return (name != null ? new PropertiesPropertySource(name, properties) : new PropertiesPropertySource(resource.getResource().getFilename(), properties));
  30. }
  31. }
  • Account.java
  1. package com.sunxiaping.spring5.domain;
  2. import java.io.Serializable;
  3. public class Account implements Serializable {
  4. private Integer id;
  5. private String name;
  6. private Double money;
  7. public Account() {
  8. }
  9. public Account(Integer id, String name, Double money) {
  10. this.id = id;
  11. this.name = name;
  12. this.money = money;
  13. }
  14. public Integer getId() {
  15. return id;
  16. }
  17. public void setId(Integer id) {
  18. this.id = id;
  19. }
  20. public String getName() {
  21. return name;
  22. }
  23. public void setName(String name) {
  24. this.name = name;
  25. }
  26. public Double getMoney() {
  27. return money;
  28. }
  29. public void setMoney(Double money) {
  30. this.money = money;
  31. }
  32. @Override
  33. public String toString() {
  34. return "Account{" +
  35. "id=" + id +
  36. ", name='" + name + '\'' +
  37. ", money=" + money +
  38. '}';
  39. }
  40. }
  • AccountDao.java
  1. package com.sunxiaping.spring5.dao;
  2. import com.sunxiaping.spring5.domain.Account;
  3. public interface AccountDao {
  4. /**
  5. * 保存账户信息
  6. *
  7. * @param account
  8. */
  9. void save(Account account);
  10. /**
  11. * 根据id查询账户信息
  12. *
  13. * @param id
  14. * @return
  15. */
  16. Account findById(Integer id);
  17. /**
  18. * 更新账户信息
  19. *
  20. * @param account
  21. */
  22. void update(Account account);
  23. /**
  24. * 删除账户信息
  25. *
  26. * @param id
  27. */
  28. void delete(Integer id);
  29. /**
  30. * 根据名称查询用户信息
  31. *
  32. * @param name
  33. * @return
  34. */
  35. Account findByName(String name);
  36. }
  • AccountDaoImpl.java
  1. package com.sunxiaping.spring5.dao.impl;
  2. import com.sunxiaping.spring5.dao.AccountDao;
  3. import com.sunxiaping.spring5.domain.Account;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import org.springframework.stereotype.Repository;
  8. import org.springframework.util.CollectionUtils;
  9. import java.util.List;
  10. @Repository
  11. public class AccountDaoImpl implements AccountDao {
  12. @Autowired
  13. private JdbcTemplate jdbcTemplate;
  14. @Override
  15. public void save(Account account) {
  16. jdbcTemplate.update(" INSERT INTO `account` (`name`,`money`) VALUES (?,?) ", account.getName(), account.getMoney());
  17. }
  18. @Override
  19. public Account findById(Integer id) {
  20. List<Account> accountList = jdbcTemplate.query(" SELECT * FROM `account` WHERE id = ? ", new BeanPropertyRowMapper<>(Account.class), id);
  21. if (CollectionUtils.isEmpty(accountList)) {
  22. return null;
  23. }
  24. return accountList.get(0);
  25. }
  26. @Override
  27. public void update(Account account) {
  28. jdbcTemplate.update(" UPDATE `account` set name =?,money =? WHERE id = ? ", account.getName(), account.getMoney(), account.getId());
  29. }
  30. @Override
  31. public void delete(Integer id) {
  32. jdbcTemplate.update(" DELETE FROM account WHERE id = ? ", id);
  33. }
  34. @Override
  35. public Account findByName(String name) {
  36. List<Account> accountList = jdbcTemplate.query(" SELECT * FROM `account` WHERE name = ? ", new BeanPropertyRowMapper<>(Account.class), name);
  37. if (CollectionUtils.isEmpty(accountList)) {
  38. return null;
  39. }
  40. if (accountList.size() > 1) {
  41. throw new RuntimeException("名称name不唯一");
  42. }
  43. return accountList.get(0);
  44. }
  45. }
  • 事务管理器TransactionManager
  1. package com.sunxiaping.spring5.utils;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Component;
  4. import java.sql.Connection;
  5. import java.sql.SQLException;
  6. @Component
  7. public class TransactionManager {
  8. @Autowired
  9. private Connection connection;
  10. /**
  11. * 开始事务
  12. */
  13. public void begin() {
  14. try {
  15. connection.setAutoCommit(false);
  16. } catch (SQLException throwables) {
  17. throwables.printStackTrace();
  18. }
  19. }
  20. /**
  21. * 提交事务
  22. */
  23. public void commit() {
  24. try {
  25. connection.commit();
  26. } catch (SQLException throwables) {
  27. throwables.printStackTrace();
  28. }
  29. }
  30. /**
  31. * 回滚事务
  32. */
  33. public void rollback() {
  34. try {
  35. connection.rollback();
  36. } catch (SQLException throwables) {
  37. throwables.printStackTrace();
  38. }
  39. }
  40. /**
  41. * 释放资源
  42. */
  43. public void close() {
  44. try {
  45. connection.close();
  46. } catch (SQLException throwables) {
  47. throwables.printStackTrace();
  48. }
  49. }
  50. }
  • JdbcConfig.java
  1. package com.sunxiaping.spring5.config;
  2. import com.alibaba.druid.pool.DruidDataSource;
  3. import com.sunxiaping.spring5.factory.YAMLPropertySourceFactory;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.context.annotation.PropertySource;
  8. import org.springframework.jdbc.datasource.DataSourceUtils;
  9. import org.springframework.transaction.support.TransactionSynchronizationManager;
  10. import javax.sql.DataSource;
  11. import java.sql.Connection;
  12. @Configuration
  13. @PropertySource(value = "classpath:jdbc.yml",factory = YAMLPropertySourceFactory.class)
  14. public class JdbcConfig {
  15. @Value("${jdbc.url}")
  16. private String url;
  17. @Value("${jdbc.driver}")
  18. private String driver;
  19. @Value("${jdbc.user}")
  20. private String user;
  21. @Value("${jdbc.password}")
  22. private String password;
  23. /**配置数据源
  24. * @return
  25. */
  26. @Bean
  27. public DataSource dataSource(){
  28. DruidDataSource dataSource = new DruidDataSource();
  29. dataSource.setDriverClassName(driver);
  30. dataSource.setUrl(url);
  31. dataSource.setUsername(user);
  32. dataSource.setPassword(password);
  33. return dataSource;
  34. }
  35. @Bean
  36. public Connection getConnection(DataSource dataSource){
  37. //初始化事务同步管理器
  38. TransactionSynchronizationManager.initSynchronization();
  39. //使用Spring的数据源工具类获取当前线程的连接
  40. Connection connection = DataSourceUtils.getConnection(dataSource);
  41. //返回连接
  42. return connection;
  43. }
  44. }
  • SpringConfig.java
  1. package com.sunxiaping.spring5.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.ComponentScan;
  4. import org.springframework.context.annotation.Configuration;
  5. import org.springframework.context.annotation.Import;
  6. import org.springframework.jdbc.core.JdbcTemplate;
  7. import javax.sql.DataSource;
  8. /**
  9. * Spring的配置类
  10. */
  11. @Configuration
  12. @Import({JdbcConfig.class})
  13. @ComponentScan(value = "com.sunxiaping")
  14. public class SpringConfig {
  15. @Bean
  16. public JdbcTemplate jdbcTemplate(DataSource dataSource){
  17. return new JdbcTemplate(dataSource);
  18. }
  19. }

1.2.2 没有动态代理的情况下实现事务管理

  • AccountService.java
  1. package com.sunxiaping.spring5.service;
  2. public interface AccountService {
  3. /**
  4. * 转账
  5. *
  6. * @param sourceName 转出账户名称
  7. * @param targetName 转入账户名称
  8. * @param money 金额
  9. */
  10. void transfer(String sourceName, String targetName, Double money);
  11. }
  • AccountServiceImpl.java
  1. package com.sunxiaping.spring5.service.impl;
  2. import com.sunxiaping.spring5.dao.AccountDao;
  3. import com.sunxiaping.spring5.domain.Account;
  4. import com.sunxiaping.spring5.service.AccountService;
  5. import com.sunxiaping.spring5.utils.TransactionManager;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. @Service
  9. public class AccountServiceImpl implements AccountService {
  10. @Autowired
  11. private AccountDao accountDao;
  12. @Autowired
  13. private TransactionManager transactionManager;
  14. @Override
  15. public void transfer(String sourceName, String targetName, Double money) {
  16. try {
  17. //开启事务
  18. transactionManager.begin();
  19. //查询转出账户
  20. Account source = accountDao.findByName(sourceName);
  21. //查询转入账户
  22. Account target = accountDao.findByName(targetName);
  23. //转出账户减钱
  24. source.setMoney(source.getMoney() - money);
  25. //转入账户加钱
  26. target.setMoney(target.getMoney() + money);
  27. //更新账户
  28. accountDao.update(source);
  29. //模拟异常
  30. int num = 10 / 0;
  31. accountDao.update(target);
  32. //提交事务
  33. transactionManager.commit();
  34. } catch (Exception e) {
  35. //回滚事务
  36. transactionManager.rollback();
  37. e.printStackTrace();
  38. } finally {
  39. //释放连接
  40. transactionManager.close();
  41. }
  42. }
  43. }
  • 测试:
  1. package com.sunxiaping.spring5;
  2. import com.sunxiaping.spring5.config.SpringConfig;
  3. import com.sunxiaping.spring5.service.AccountService;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.test.context.ContextConfiguration;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9. @RunWith(SpringJUnit4ClassRunner.class)
  10. @ContextConfiguration(classes = SpringConfig.class)
  11. public class Spring5Test {
  12. @Autowired
  13. private AccountService accountService;
  14. @Test
  15. public void test() {
  16. accountService.transfer("张三","李四",100d);
  17. }
  18. }

在没有动态代理实现事务管理的情况下,几乎每个方法都需要写事务开启、事务提交、事务回滚和释放资源的代码,太繁琐了。

1.2.3 动态代理实现事务管理

  • AccountService.java
  1. package com.sunxiaping.spring5.service;
  2. public interface AccountService {
  3. /**
  4. * 转账
  5. *
  6. * @param sourceName 转出账户名称
  7. * @param targetName 转入账户名称
  8. * @param money 金额
  9. */
  10. void transfer(String sourceName, String targetName, Double money);
  11. }
  • AccountServiceImpl.java
  1. package com.sunxiaping.spring5.service.impl;
  2. import com.sunxiaping.spring5.dao.AccountDao;
  3. import com.sunxiaping.spring5.domain.Account;
  4. import com.sunxiaping.spring5.service.AccountService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. @Service
  8. public class AccountServiceImpl implements AccountService {
  9. @Autowired
  10. private AccountDao accountDao;
  11. @Override
  12. public void transfer(String sourceName, String targetName, Double money) {
  13. //查询转出账户
  14. Account source = accountDao.findByName(sourceName);
  15. //查询转入账户
  16. Account target = accountDao.findByName(targetName);
  17. //转出账户减钱
  18. source.setMoney(source.getMoney() - money);
  19. //转入账户加钱
  20. target.setMoney(target.getMoney() + money);
  21. //更新账户
  22. accountDao.update(source);
  23. //模拟异常
  24. int num = 10 / 0;
  25. accountDao.update(target);
  26. }
  27. }
  • ProxyServiceFactory.java
  1. package com.sunxiaping.spring5.factory;
  2. import com.sunxiaping.spring5.service.AccountService;
  3. import com.sunxiaping.spring5.utils.TransactionManager;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.stereotype.Component;
  7. import java.lang.reflect.Proxy;
  8. /**
  9. * 实现对AccountService的代理创建,同时加入事务
  10. */
  11. @Component
  12. public class ProxyServiceFactory {
  13. @Autowired
  14. private AccountService accountService;
  15. @Autowired
  16. private TransactionManager transactionManager;
  17. @Bean("proxyAccountService")
  18. public AccountService proxyAccountService() {
  19. //创建代理对象
  20. AccountService proxy = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), (proxy1, method, args) -> {
  21. Object result = null;
  22. try {
  23. //开启事务
  24. transactionManager.begin();
  25. result = method.invoke(accountService, args);
  26. //提交事务
  27. transactionManager.commit();
  28. } catch (Exception e) {
  29. //回滚事务
  30. transactionManager.rollback();
  31. e.printStackTrace();
  32. } finally {
  33. //释放资源
  34. transactionManager.close();
  35. }
  36. return result;
  37. });
  38. return proxy;
  39. }
  40. }
  • 测试:
  1. package com.sunxiaping.spring5;
  2. import com.sunxiaping.spring5.config.SpringConfig;
  3. import com.sunxiaping.spring5.service.AccountService;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Qualifier;
  8. import org.springframework.test.context.ContextConfiguration;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10. @RunWith(SpringJUnit4ClassRunner.class)
  11. @ContextConfiguration(classes = SpringConfig.class)
  12. public class Spring5Test {
  13. @Autowired
  14. @Qualifier(value = "proxyAccountService")
  15. private AccountService accountService;
  16. @Test
  17. public void test() {
  18. accountService.transfer("张三","李四",100d);
  19. }
  20. }

第二章:AOP思想及实现原理

2.1 AOP思想

  • 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

2.2 实现原理

  • 在上面的概念中描述出的AOP的实现原理是基于动态代理技术实现的。
  • 动态代理的特点:字节码随用随创建,随用随加载。
  • 动态代理的分类:基于接口的动态代理,基于子类的动态代理。
  • 动态代理的作用:不修改源码的基础上对方法进行增强。
  • 基于接口的动态代理:JDK官方。
  • 基于子类的动态代理:第三方CGLIB包。

2.3 Spring中的AOP术语

  • Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在Spring中,指的是方法,因为Spring只支持方法类型的连接点。
  • Pointcut(切入点):所谓切入点是指我们要对那些Pointcut进行拦截的定义。
  • Advice(通知/增强):
    • 所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。
    • 通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
  • Introduction(引介):引介是一种特殊的通知,在不修改类代码的前提下,可以在运行期为类动态的添加一个方法或属性。
  • Target(目标对象):代理的目标对象。
  • Weaving(织入):
    • 是指把增强应用到目标对象来创建新的代理对象的过程。
    • Spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
  • Proxy(代理):一个类被AOP织入增强后,就产生了一个结果代理类。
  • Aspect(切面):是切入点和通知(引介)的结合。

第三章:Spring注解驱动AOP开发入门

3.1 注解驱动AOP入门案例介绍

  • 实现在执行Service方法时输出日志。

3.2 案例实现

  • 导入相关jar包的Maven坐标:
  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-context</artifactId>
  4. <version>5.2.7.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>org.springframework</groupId>
  8. <artifactId>spring-web</artifactId>
  9. <version>5.2.7.RELEASE</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework</groupId>
  13. <artifactId>spring-webmvc</artifactId>
  14. <version>5.2.7.RELEASE</version>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework</groupId>
  18. <artifactId>spring-aspects</artifactId>
  19. <version>5.2.7.RELEASE</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework</groupId>
  23. <artifactId>spring-aop</artifactId>
  24. <version>5.2.7.RELEASE</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>com.alibaba</groupId>
  28. <artifactId>druid</artifactId>
  29. <version>1.1.23</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.springframework</groupId>
  33. <artifactId>spring-jdbc</artifactId>
  34. <version>5.2.7.RELEASE</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework</groupId>
  38. <artifactId>spring-test</artifactId>
  39. <version>5.2.7.RELEASE</version>
  40. </dependency>
  41. <dependency>
  42. <groupId>mysql</groupId>
  43. <artifactId>mysql-connector-java</artifactId>
  44. <version>8.0.19</version>
  45. </dependency>
  46. <!-- 导入YAML解析工厂坐标 -->
  47. <dependency>
  48. <groupId>org.yaml</groupId>
  49. <artifactId>snakeyaml</artifactId>
  50. <version>1.26</version>
  51. </dependency>
  52. <dependency>
  53. <groupId>junit</groupId>
  54. <artifactId>junit</artifactId>
  55. <version>4.13</version>
  56. <scope>test</scope>
  57. </dependency>
  58. <dependency>
  59. <groupId>javax.inject</groupId>
  60. <artifactId>javax.inject</artifactId>
  61. <version>1</version>
  62. </dependency>
  63. <dependency>
  64. <groupId>javax.annotation</groupId>
  65. <artifactId>javax.annotation-api</artifactId>
  66. <version>1.3.2</version>
  67. </dependency>
  68. <dependency>
  69. <groupId>javax.servlet</groupId>
  70. <artifactId>javax.servlet-api</artifactId>
  71. <version>4.0.1</version>
  72. </dependency>
  • 实体类User.java
  1. package com.sunxiaping.spring5.domain;
  2. import java.io.Serializable;
  3. import java.util.Date;
  4. public class User implements Serializable {
  5. private String id;
  6. private String username;
  7. private String password;
  8. private Date birthday;
  9. private String gender;
  10. private String mobile;
  11. private String nickname;
  12. public String getId() {
  13. return id;
  14. }
  15. public void setId(String id) {
  16. this.id = id;
  17. }
  18. public String getUsername() {
  19. return username;
  20. }
  21. public void setUsername(String username) {
  22. this.username = username;
  23. }
  24. public String getPassword() {
  25. return password;
  26. }
  27. public void setPassword(String password) {
  28. this.password = password;
  29. }
  30. public Date getBirthday() {
  31. return birthday;
  32. }
  33. public void setBirthday(Date birthday) {
  34. this.birthday = birthday;
  35. }
  36. public String getGender() {
  37. return gender;
  38. }
  39. public void setGender(String gender) {
  40. this.gender = gender;
  41. }
  42. public String getMobile() {
  43. return mobile;
  44. }
  45. public void setMobile(String mobile) {
  46. this.mobile = mobile;
  47. }
  48. public String getNickname() {
  49. return nickname;
  50. }
  51. public void setNickname(String nickname) {
  52. this.nickname = nickname;
  53. }
  54. @Override
  55. public String toString() {
  56. return "User{" +
  57. "id='" + id + '\'' +
  58. ", username='" + username + '\'' +
  59. ", password='" + password + '\'' +
  60. ", birthday=" + birthday +
  61. ", gender='" + gender + '\'' +
  62. ", mobile='" + mobile + '\'' +
  63. ", nickname='" + nickname + '\'' +
  64. '}';
  65. }
  66. }
  • 业务层接口UserService.java
  1. package com.sunxiaping.spring5.service;
  2. import com.sunxiaping.spring5.domain.User;
  3. public interface UserService {
  4. /**
  5. * 模拟保存用户信息
  6. *
  7. * @param user
  8. */
  9. void saveUser(User user);
  10. }
  • 业务层实现类UserServiceImpl.java
  1. package com.sunxiaping.spring5.service.impl;
  2. import com.sunxiaping.spring5.domain.User;
  3. import com.sunxiaping.spring5.service.UserService;
  4. import org.springframework.stereotype.Service;
  5. @Service("userService")
  6. public class UserServiceImpl implements UserService {
  7. @Override
  8. public void saveUser(User user) {
  9. System.out.println("保存用户信息" + user);
  10. }
  11. }
  • 切面类LogUtil.java
  1. package com.sunxiaping.spring5.utils;
  2. import org.aspectj.lang.annotation.Aspect;
  3. import org.aspectj.lang.annotation.Before;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. @Aspect //表明当前类是一个切面类
  7. public class LogUtil {
  8. @Before(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  9. public void printLog() {
  10. System.out.println("输出日志");
  11. }
  12. }
  • Spring的配置类SpringConfig.java
  1. package com.sunxiaping.spring5.config;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.EnableAspectJAutoProxy;
  5. /**
  6. * Spring的配置类
  7. */
  8. @Configuration
  9. @ComponentScan(value = "com.sunxiaping.spring5")
  10. @EnableAspectJAutoProxy //开启Spring的AOP注解的支持
  11. public class SpringConfig {
  12. }
  • 测试:
  1. package com.sunxiaping.spring5;
  2. import com.sunxiaping.spring5.config.SpringConfig;
  3. import com.sunxiaping.spring5.domain.User;
  4. import com.sunxiaping.spring5.service.UserService;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.test.context.ContextConfiguration;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10. import java.util.Date;
  11. import java.util.UUID;
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration(classes = SpringConfig.class)
  14. public class Spring5Test {
  15. @Autowired
  16. private UserService userService;
  17. @Test
  18. public void test() {
  19. User user = new User();
  20. user.setId(UUID.randomUUID().toString());
  21. user.setUsername("张三");
  22. user.setPassword("123456");
  23. user.setBirthday(new Date());
  24. user.setGender("男");
  25. user.setMobile("110");
  26. user.setNickname("唐三葬");
  27. userService.saveUser(user);
  28. }
  29. }

第四章:AOP常用注解分析

4.1 用于开启注解AOP注解的注解

4.1.1 @EnableAspectJAutoProxy注解

  • @EnableAspectJAutoProxy注解:
  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Import(AspectJAutoProxyRegistrar.class)
  5. public @interface EnableAspectJAutoProxy {
  6. /**
  7. * Indicate whether subclass-based (CGLIB) proxies are to be created as opposed
  8. * to standard Java interface-based proxies. The default is {@code false}.
  9. */
  10. boolean proxyTargetClass() default false;
  11. /**
  12. * Indicate that the proxy should be exposed by the AOP framework as a {@code ThreadLocal}
  13. * for retrieval via the {@link org.springframework.aop.framework.AopContext} class.
  14. * Off by default, i.e. no guarantees that {@code AopContext} access will work.
  15. * @since 4.3.1
  16. */
  17. boolean exposeProxy() default false;
  18. }
  • 作用:
    • 表明开启Spring对注解AOP的支持。它有两个属性,分别是指定采用的代理方式和是否暴露代理对象,通过AopContext可以进行访问。从定义中可以看出,它引入AspectJAutoProxyRegistrar的字节码对象,该对象是基于注解@EnableAspectJAutoProxy注册了一个AnnotationAwareAspectJAutoProxyCreator,该对象通过调用AopConfigUtils的registerAspectJAnnotationAutoProxyCreatorIfNecessary(registry):注册一个AOP代理对象生成器。
  • 属性:
    • proxyTargetClass:指定是否采用CGLIB进行代理。默认值是false,表示使用JDK的代理。
    • exposeProxy:指定是否暴露代理对象,通过AopContext可以进行访问。
  • 使用场景:当我们注解驱动开发的时候,在需要使用AOP实现某些功能的情况下,都需要用到此注解。

  • 示例:

  1. package com.sunxiaping.spring5.config;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.EnableAspectJAutoProxy;
  5. /**
  6. * Spring的配置类
  7. */
  8. @Configuration
  9. @ComponentScan(value = "com.sunxiaping.spring5")
  10. @EnableAspectJAutoProxy //开启Spring的AOP注解的支持
  11. public class SpringConfig {
  12. }

4.2 用于配置切面的注解

4.2.1 @Aspect注解

  • @Aspect注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.TYPE)
  3. public @interface Aspect {
  4. /**
  5. * @return the per clause expression, defaults to singleton aspect.
  6. * Valid values are "" (singleton), "perthis(...)", etc
  7. */
  8. public String value() default "";
  9. }
  • 作用:声明当前类是一个切面类。
  • 属性:
    • value:支持指定切入点表达式,或者用@Pointcut修改的方法名称(要求全限定方法名)。
  • 使用场景:此注解也是一个注解驱动开发AOP的必备注解。

  • 示例:

  1. package com.sunxiaping.spring5.utils;
  2. import org.aspectj.lang.annotation.Aspect;
  3. import org.aspectj.lang.annotation.Before;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. @Aspect //表明当前类是一个切面类
  7. public class LogUtil {
  8. @Before(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  9. public void printLog() {
  10. System.out.println("输出日志");
  11. }
  12. }

4.2.2 @Order注解

  • @Order注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
  3. @Documented
  4. public @interface Order {
  5. /**
  6. * The order value.
  7. * <p>Default is {@link Ordered#LOWEST_PRECEDENCE}.
  8. * @see Ordered#getOrder()
  9. */
  10. int value() default Ordered.LOWEST_PRECEDENCE;
  11. }
  • 作用:@Order注解是定义Spring的IOC容器中的Bean的执行顺序的优先级。
  • 属性:
    • value:最低优先级,值越小,优先级越高。
  • 使用场景:可以改变默认的Spring加载多个切面的执行顺序(默认情况下是按照切面类名的自然顺序排序)。

  • 示例:

  • UserService.java
  1. package com.sunxiaping.spring5.service;
  2. import com.sunxiaping.spring5.domain.User;
  3. public interface UserService {
  4. /**
  5. * 模拟保存用户信息
  6. *
  7. * @param user
  8. */
  9. void saveUser(User user);
  10. }
  • UserServiceImpl.java
  1. package com.sunxiaping.spring5.service.impl;
  2. import com.sunxiaping.spring5.domain.User;
  3. import com.sunxiaping.spring5.service.UserService;
  4. import org.springframework.stereotype.Service;
  5. @Service("userService")
  6. public class UserServiceImpl implements UserService {
  7. @Override
  8. public void saveUser(User user) {
  9. try {
  10. Thread.sleep(2000);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }
  14. System.out.println("保存用户信息" + user);
  15. }
  16. }
  • LogUtil.java
  1. package com.sunxiaping.spring5.utils;
  2. import org.aspectj.lang.annotation.Aspect;
  3. import org.aspectj.lang.annotation.Before;
  4. import org.springframework.core.annotation.Order;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * 日志工具类
  8. */
  9. @Component
  10. @Aspect
  11. @Order(1)
  12. public class LogUtil {
  13. @Before(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  14. public void printLog() {
  15. System.out.println("输出日志");
  16. }
  17. }
  • EfficiencyUtil.java
  1. package com.sunxiaping.spring5.utils;
  2. import org.aspectj.lang.annotation.After;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.springframework.core.annotation.Order;
  6. import org.springframework.stereotype.Component;
  7. import java.time.Duration;
  8. import java.time.LocalDateTime;
  9. /**
  10. * 方法效率的工具类
  11. */
  12. @Component
  13. @Aspect
  14. @Order(2)
  15. public class EfficiencyUtil {
  16. private LocalDateTime startTime;
  17. /**
  18. * 记录方法执行之前的时间
  19. */
  20. @Before(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  21. public void printBeforeExecutionTime() {
  22. startTime = LocalDateTime.now();
  23. System.out.println("方法开始执行时间 = " + startTime);
  24. }
  25. /**
  26. * 记录方法执行之后的时间
  27. */
  28. @After(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  29. public void printAfterExecutionTime() {
  30. LocalDateTime endTime = LocalDateTime.now();
  31. System.out.println("方法结束执行时间 = " + endTime);
  32. Duration duration = Duration.between(startTime, endTime);
  33. System.out.println("方法执行的时间 = " + duration.getSeconds() );
  34. }
  35. }
  • 测试:
  1. package com.sunxiaping.spring5;
  2. import com.sunxiaping.spring5.config.SpringConfig;
  3. import com.sunxiaping.spring5.domain.User;
  4. import com.sunxiaping.spring5.service.UserService;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.test.context.ContextConfiguration;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10. import java.util.Date;
  11. import java.util.UUID;
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration(classes = SpringConfig.class)
  14. public class Spring5Test {
  15. @Autowired
  16. private UserService userService;
  17. @Test
  18. public void test() {
  19. User user = new User();
  20. user.setId(UUID.randomUUID().toString());
  21. user.setUsername("张三");
  22. user.setPassword("123456");
  23. user.setBirthday(new Date());
  24. user.setGender("男");
  25. user.setMobile("110");
  26. user.setNickname("唐三葬");
  27. userService.saveUser(user);
  28. }
  29. }

4.3 用于配置切入点表达式的注解

4.3.1 @Pointcut注解

  • @Pointcut注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface Pointcut {
  4. /**
  5. * @return the pointcut expression
  6. * We allow "" as default for abstract pointcut
  7. */
  8. String value() default "";
  9. /**
  10. * When compiling without debug info, or when interpreting pointcuts at runtime,
  11. * the names of any arguments used in the pointcut are not available.
  12. * Under these circumstances only, it is necessary to provide the arg names in
  13. * the annotation - these MUST duplicate the names used in the annotated method.
  14. * Format is a simple comma-separated list.
  15. *
  16. * @return argNames the argument names (should match those in the annotated method)
  17. */
  18. String argNames() default "";
  19. }
  • 作用:此注解是用于指定切入点表达式的。
  • 属性:
    • value:用于指定切入点表达式。
    • argNames:用于指定切入点表达式中的参数。参数可以是execution中的,也可以是args中的。通常情况下不使用此属性也可以获得切入点的方法参数。
  • 使用场景:在实际开发中,当我们的多个通知需要执行。

  • 示例:

  • LogUtil.java
  1. package com.sunxiaping.spring5.utils;
  2. import com.sunxiaping.spring5.domain.User;
  3. import org.aspectj.lang.annotation.Aspect;
  4. import org.aspectj.lang.annotation.Before;
  5. import org.aspectj.lang.annotation.Pointcut;
  6. import org.springframework.core.annotation.Order;
  7. import org.springframework.stereotype.Component;
  8. /**
  9. * 日志工具类
  10. */
  11. @Component
  12. @Aspect
  13. @Order(1)
  14. public class LogUtil {
  15. /**
  16. * 用于定义通用的切入点表达式
  17. * 在value属性中使用了&&符号,表示并且的关系。
  18. * &&符号后面的args和execution一样,都是切入点表达式支持的关键字,表示匹配参数。指定的内容可以是全限定类名或者名称,当指定参数名称时,要求和方法中形参名称相同。
  19. * argNames属性,是定义参数的名称,该名称必须和args关键字中的名称一致。
  20. */
  21. @Pointcut(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..)) && args(user))", argNames = "user")
  22. public void pointcut(User user) {
  23. }
  24. @Before(value = "pointcut(user)", argNames = "user")
  25. public void printLog(User user) {
  26. System.out.println("输出日志" + user);
  27. }
  28. }

4.4 用于配置通知的注解

4.4.1 @Before注解

  • @Before注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface Before {
  4. /**
  5. * @return the pointcut expression where to bind the advice
  6. */
  7. String value();
  8. /**
  9. * When compiling without debug info, or when interpreting pointcuts at runtime,
  10. * the names of any arguments used in the advice declaration are not available.
  11. * Under these circumstances only, it is necessary to provide the arg names in
  12. * the annotation - these MUST duplicate the names used in the annotated method.
  13. * Format is a simple comma-separated list.
  14. *
  15. * @return the argument names (should match the annotated method parameter names)
  16. */
  17. String argNames() default "";
  18. }
  • 作用:被此注解修改的方法为前置通知。前置通知的执行时间点实在切入点方法执行之前。
  • 属性:
    • value:用于指定切入点表达式。可以是表达式,也可以是表达式的引用。
    • argNames:用于指定切入点表达式参数的名称。它要求和切入点表达式中的参数名称一致。通常不指定也可以获取切入点的参数内容。
  • 使用场景:

    • 在实际开发中,我们需要对切入点方法执行之前进行增强,此时就需要用到前置通知。在通知(增强的方法)中获取切入点方法中的参数进行处理时,就需要配合切入点表达式参数来使用。
  • 示例:略。

4.4.2 @AfterReturning注解

  • @AfterReturning注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface AfterReturning {
  4. /**
  5. * @return the pointcut expression where to bind the advice
  6. */
  7. String value() default "";
  8. /**
  9. * @return the pointcut expression where to bind the advice, overrides "value" when specified
  10. */
  11. String pointcut() default "";
  12. /**
  13. * @return the name of the argument in the advice signature to bind the returned value to
  14. */
  15. String returning() default "";
  16. /**
  17. * When compiling without debug info, or when interpreting pointcuts at runtime,
  18. * the names of any arguments used in the advice declaration are not available.
  19. * Under these circumstances only, it is necessary to provide the arg names in
  20. * the annotation - these MUST duplicate the names used in the annotated method.
  21. * Format is a simple comma-separated list.
  22. * @return the argument names (that should match names used in the annotated method)
  23. */
  24. String argNames() default "";
  25. }
  • 作用:
    • 用于配置后置通知。
    • 后置通知的执行时在切入点正常执行之后执行。
  • 属性:
    • value:用于指定切入点表达式,可以是表达式,也可以是表达式的引用。
    • pointcut:它的作用和value是一样的。
    • returning:指定切入点方法返回值的变量名称。它必须和切入点方法返回值名称一致。
    • argNames:用于指定切入点表达式参数的名称。它要求和切入点表达式中的参数名称一致。通常不指定也可以获取切入点的参数内容。
  • 使用场景:

    • 此注解是用于配置后置增强切入点方法的。被此注解修饰方法会在切入点方法正常执行之后执行。
    • 在我们实际中,像提交事务,记录访问日志,统计方法执行效率等等都可以利用后置通知实现。
  • 示例:略。

4.4.3 @AfterThrowing注解

  • @AfterThrowing注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface AfterThrowing {
  4. /**
  5. * @return the pointcut expression where to bind the advice
  6. */
  7. String value() default "";
  8. /**
  9. * @return the pointcut expression where to bind the advice, overrides "value" when specified
  10. */
  11. String pointcut() default "";
  12. /**
  13. * @return the name of the argument in the advice signature to bind the thrown exception to
  14. */
  15. String throwing() default "";
  16. /**
  17. * When compiling without debug info, or when interpreting pointcuts at runtime,
  18. * the names of any arguments used in the advice declaration are not available.
  19. * Under these circumstances only, it is necessary to provide the arg names in
  20. * the annotation - these MUST duplicate the names used in the annotated method.
  21. * Format is a simple comma-separated list.
  22. * @return the argument names (that should match names used in the annotated method)
  23. */
  24. String argNames() default "";
  25. }
  • 作用:用于配置异常通知。
  • 属性:

    • value:用于指定切入点表达式,可以是表达式,也可以是表达式的引用。
    • pointcut:它的作用和value是一样的。
    • throwing:指定切入点方法执行产生异常时的异常对象变量名称。它必须和异常变量名称一致。
    • argNames:用于指定切入点表达式参数的名称。它要求和切入点表达式中的参数名称一致。通常不指定也可以获取切入点的参数内容。
  • 示例:略。

4.4.4 @After注解

  • @After注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface After {
  4. /**
  5. * @return the pointcut expression where to bind the advice
  6. */
  7. String value();
  8. /**
  9. * When compiling without debug info, or when interpreting pointcuts at runtime,
  10. * the names of any arguments used in the advice declaration are not available.
  11. * Under these circumstances only, it is necessary to provide the arg names in
  12. * the annotation - these MUST duplicate the names used in the annotated method.
  13. * Format is a simple comma-separated list.
  14. *
  15. * @return the argument names (should duplicate the names used for the annotated method parameters)
  16. */
  17. String argNames() default "";
  18. }
  • 作用:用于指定最终通知。
  • 属性:
    • value:用于指定切入点表达式,可以是表达式,也可以是表达式的引用。
    • argNames:用于指定切入点表达式参数的名称。它要求和切入点表达式中的参数名称一致。通常不指定也可以获取切入点的参数内容。
  • 使用场景:最终通知的执行时机,是在切入点方法执行完成之后执行,无论切入点方法执行是否产生异常最终通知都会执行。所以被此直接修饰的方法,通常都是做一些清理工作。

  • 示例:

  • UserService.java
  1. package com.sunxiaping.spring5.service;
  2. import com.sunxiaping.spring5.domain.User;
  3. public interface UserService {
  4. /**
  5. * 模拟保存用户信息
  6. *
  7. * @param user
  8. */
  9. void saveUser(User user);
  10. }
  • UserServiceImpl.java
  1. package com.sunxiaping.spring5.service.impl;
  2. import com.sunxiaping.spring5.domain.User;
  3. import com.sunxiaping.spring5.service.UserService;
  4. import org.springframework.stereotype.Service;
  5. @Service("userService")
  6. public class UserServiceImpl implements UserService {
  7. @Override
  8. public void saveUser(User user) {
  9. // int i = 10 / 0;
  10. System.out.println("保存用户信息" + user);
  11. }
  12. }
  • LogUtil.java
  1. package com.sunxiaping.spring5.utils;
  2. import org.aspectj.lang.annotation.*;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * 日志工具类
  6. */
  7. @Component
  8. @Aspect
  9. public class LogUtil {
  10. @Before(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  11. public void beforePrintLog() {
  12. System.out.println("前置通知:输出日志");
  13. }
  14. @After(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  15. public void afterPrintLog() {
  16. System.out.println("最终通知:输出日志");
  17. }
  18. @AfterReturning(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))", returning = "obj")
  19. public void afterReturningPrintLog(Object obj) {
  20. System.out.println("后置通知:输出日志" + obj);
  21. }
  22. @AfterThrowing(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))", throwing = "ex")
  23. public void afterThrowingPrintLog(Throwable ex) {
  24. System.out.println("异常通知:输出日志" + ex);
  25. }
  26. }
  • SpringConfig.java
  1. package com.sunxiaping.spring5.config;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.EnableAspectJAutoProxy;
  5. /**
  6. * Spring的配置类
  7. */
  8. @Configuration
  9. @ComponentScan(value = "com.sunxiaping.spring5")
  10. @EnableAspectJAutoProxy //开启Spring的AOP注解的支持
  11. public class SpringConfig {
  12. }
  • 测试:
  1. package com.sunxiaping.spring5;
  2. import com.sunxiaping.spring5.config.SpringConfig;
  3. import com.sunxiaping.spring5.domain.User;
  4. import com.sunxiaping.spring5.service.UserService;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.test.context.ContextConfiguration;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10. import java.util.Date;
  11. @RunWith(SpringJUnit4ClassRunner.class)
  12. @ContextConfiguration(classes = SpringConfig.class)
  13. public class Spring5Test {
  14. @Autowired
  15. private UserService userService;
  16. @Test
  17. public void test() {
  18. User user = new User();
  19. user.setId("1");
  20. user.setUsername("张三");
  21. user.setPassword("123456");
  22. user.setBirthday(new Date());
  23. user.setGender("男");
  24. user.setMobile("110");
  25. user.setNickname("唐三葬");
  26. userService.saveUser(user);
  27. }
  28. }

4.4.5 @Around注解

  • @Around注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.METHOD)
  3. public @interface Around {
  4. /**
  5. * @return the pointcut expression where to bind the advice
  6. */
  7. String value();
  8. /**
  9. * When compiling without debug info, or when interpreting pointcuts at runtime,
  10. * the names of any arguments used in the advice declaration are not available.
  11. * Under these circumstances only, it is necessary to provide the arg names in
  12. * the annotation - these MUST duplicate the names used in the annotated method.
  13. * Format is a simple comma-separated list.
  14. * @return the argument names (should match the names on the annotated method)
  15. */
  16. String argNames() default "";
  17. }
  • 作用:用于指定环绕通知。
  • 属性:
    • value:用于指定切入点表达式,可以是表达式,也可以是表达式的引用。
    • argNames:用于指定切入点表达式参数的名称。它要求和切入点表达式中的参数名称一致。通常不指定也可以获取切入点的参数内容。
  • 使用场景:环绕通知有别于前面介绍的四种通知类型。它不是指定增强方法执行时机的,而是Spring为我们提供的一种可以通过编码的方式手动增强方法何时执行的机制。

  • 示例:

  1. package com.sunxiaping.spring5.utils;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.Around;
  4. import org.aspectj.lang.annotation.Aspect;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. @Aspect
  8. public class LogUtil {
  9. @Around(value = "execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  10. public Object printLog(ProceedingJoinPoint joinPoint) {
  11. Object proceed = null;
  12. try {
  13. System.out.println("前置通知");
  14. proceed = joinPoint.proceed();
  15. System.out.println("后置通知");
  16. } catch (Throwable throwable) {
  17. System.out.println("异常通知");
  18. throwable.printStackTrace();
  19. }finally {
  20. System.out.println("最终通知");
  21. }
  22. return proceed;
  23. }
  24. }

4.5 用于扩展目标类的注解

4.5.1 @DeclareParents注解

  • @DeclareParents注解:
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.FIELD)
  3. public @interface DeclareParents {
  4. /**
  5. * @return the target types expression
  6. */
  7. String value();
  8. /**
  9. * Optional class defining default implementation
  10. * of interface members (equivalent to defining
  11. * a set of interface member ITDs for the
  12. * public methods of the interface).
  13. *
  14. * @return define the default implementation of interface members (should always be specified)
  15. */
  16. Class defaultImpl() default DeclareParents.class;
  17. // note - a default of "null" is not allowed,
  18. // hence the strange default given above.
  19. }
  • 作用:用于给被增强的类提供新的方法。(实现新的接口)
  • 属性:
    • value:用于指定目标类型额表达式。当在全限定类名后面加上“+”时,表示当前类及其子类。
    • defaultImpl:指定提高方法或者字段的默认实现类。
  • 使用场景:当我们已经完成了一个项目的某个阶段开发,此时需要对已完成的某个类加入一些新的方法,我们首先想到的是写一个接口,然后让这些需要方法的类实现此接口,但是如果目标类非常复杂,牵一发而动全身,改动的话可能非常麻烦。此时就可以使用此注解,然后建一个代理类,同时代理该类和目标类。

  • 示例:

  • UserService.java
  1. package com.sunxiaping.spring5.service;
  2. import com.sunxiaping.spring5.domain.User;
  3. public interface UserService {
  4. /**
  5. * 模拟保存用户信息
  6. *
  7. * @param user
  8. */
  9. void saveUser(User user);
  10. }
  • UserServiceImpl.java
  1. package com.sunxiaping.spring5.service.impl;
  2. import com.sunxiaping.spring5.domain.User;
  3. import com.sunxiaping.spring5.service.UserService;
  4. import org.springframework.stereotype.Service;
  5. @Service("userService")
  6. public class UserServiceImpl implements UserService {
  7. @Override
  8. public void saveUser(User user) {
  9. System.out.println("保存用户信息" + user);
  10. }
  11. }
  • ValidateExtensionService.java
  1. package com.sunxiaping.spring5.extension;
  2. import com.sunxiaping.spring5.domain.User;
  3. /**
  4. * 用于扩展用户Service验证的接口
  5. */
  6. public interface ValidateExtensionService {
  7. /**
  8. * 检查用户信息
  9. *
  10. * @param user
  11. * @return
  12. */
  13. boolean checkUser(User user);
  14. }
  • ValidateExtensionServiceImpl.java
  1. package com.sunxiaping.spring5.extension.impl;
  2. import com.sunxiaping.spring5.domain.User;
  3. import com.sunxiaping.spring5.extension.ValidateExtensionService;
  4. import org.springframework.util.StringUtils;
  5. public class ValidateExtensionServiceImpl implements ValidateExtensionService {
  6. @Override
  7. public boolean checkUser(User user) {
  8. //判断用户昵称中是否包含"孙子"
  9. return StringUtils.isEmpty(user.getNickname()) || !user.getNickname().contains("孙子");
  10. }
  11. }
  • 测试方式一:在调用的时候将UserService看成是ValidateExtensionService
    • LogUtil.java ```java package com.sunxiaping.spring5.utils;

import com.sunxiaping.spring5.extension.ValidateExtensionService; import com.sunxiaping.spring5.extension.impl.ValidateExtensionServiceImpl; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.DeclareParents; import org.springframework.stereotype.Component;

@Component @Aspect public class LogUtil {

  1. /**
  2. * 让目标类具备当前声明接口中的方法,用的也是动态代理
  3. */
  4. @DeclareParents(value = "com.sunxiaping.spring5.service.UserService+", defaultImpl = ValidateExtensionServiceImpl.class)
  5. private ValidateExtensionService validateExtensionService;

}

  1. - 测试:
  2. ```java
  3. package com.sunxiaping.spring5;
  4. import com.sunxiaping.spring5.config.SpringConfig;
  5. import com.sunxiaping.spring5.domain.User;
  6. import com.sunxiaping.spring5.extension.ValidateExtensionService;
  7. import com.sunxiaping.spring5.service.UserService;
  8. import org.junit.Test;
  9. import org.junit.runner.RunWith;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.test.context.ContextConfiguration;
  12. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  13. import java.util.Date;
  14. import java.util.UUID;
  15. @RunWith(SpringJUnit4ClassRunner.class)
  16. @ContextConfiguration(classes = SpringConfig.class)
  17. public class SpringTest {
  18. @Autowired
  19. private UserService userService;
  20. @Test
  21. public void test() {
  22. User user = new User();
  23. user.setId(UUID.randomUUID().toString());
  24. user.setUsername("张三");
  25. user.setPassword("123456");
  26. user.setBirthday(new Date());
  27. user.setGender("男");
  28. user.setMobile("110");
  29. user.setNickname("孙子");
  30. //验证用户昵称是否合法
  31. // 把userService看成是ValidateExtensionService
  32. ValidateExtensionService validateExtensionService = (ValidateExtensionService) userService;
  33. if(validateExtensionService.checkUser(user)){
  34. userService.saveUser(user);
  35. }
  36. }
  37. }
  • 测试方式二:使用前置通知,使用this关键字,引入新目标类对象,调用方法的时候触发
    • LogUtil.java ```java package com.sunxiaping.spring5.utils;

import com.sunxiaping.spring5.domain.User; import com.sunxiaping.spring5.extension.ValidateExtensionService; import com.sunxiaping.spring5.extension.impl.ValidateExtensionServiceImpl; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.DeclareParents; import org.springframework.stereotype.Component;

@Component @Aspect public class LogUtil {

  1. /**
  2. * 让目标类具备当前声明接口中的方法,用的也是动态代理
  3. */
  4. @DeclareParents(value = "com.sunxiaping.spring5.service.UserService+", defaultImpl = ValidateExtensionServiceImpl.class)
  5. private ValidateExtensionService validateExtensionService;
  6. @Before(value = "execution(* com.sunxiaping.spring5.service.UserService.*(..)) && this(validateExtensionService) && args(user)", argNames = "user,validateExtensionService")
  7. public void beforePrintLog(User user, ValidateExtensionService validateExtensionService) {
  8. if (!validateExtensionService.checkUser(user)) {
  9. throw new RuntimeException("用户昵称非法");
  10. }
  11. System.out.println("打印日志");
  12. }

}

  1. - 测试:
  2. ```java
  3. package com.sunxiaping.spring5;
  4. import com.sunxiaping.spring5.config.SpringConfig;
  5. import com.sunxiaping.spring5.domain.User;
  6. import com.sunxiaping.spring5.service.UserService;
  7. import org.junit.Test;
  8. import org.junit.runner.RunWith;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.test.context.ContextConfiguration;
  11. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  12. import java.util.Date;
  13. import java.util.UUID;
  14. @RunWith(SpringJUnit4ClassRunner.class)
  15. @ContextConfiguration(classes = SpringConfig.class)
  16. public class SpringTest {
  17. @Autowired
  18. private UserService userService;
  19. @Test
  20. public void test() {
  21. User user = new User();
  22. user.setId(UUID.randomUUID().toString());
  23. user.setUsername("张三");
  24. user.setPassword("123456");
  25. user.setBirthday(new Date());
  26. user.setGender("男");
  27. user.setMobile("110");
  28. user.setNickname("孙子");
  29. userService.saveUser(user);
  30. }
  31. }

4.5.2 @EnableLoadTimeWeaving注解

  • @EnableLoadTimeWeaving注解:
  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Import(LoadTimeWeavingConfiguration.class)
  5. public @interface EnableLoadTimeWeaving {
  6. /**
  7. * Whether AspectJ weaving should be enabled.
  8. */
  9. AspectJWeaving aspectjWeaving() default AspectJWeaving.AUTODETECT;
  10. /**
  11. * AspectJ weaving enablement options.
  12. */
  13. enum AspectJWeaving {
  14. /**
  15. * Switches on Spring-based AspectJ load-time weaving.
  16. */
  17. ENABLED,
  18. /**
  19. * Switches off Spring-based AspectJ load-time weaving (even if a
  20. * "META-INF/aop.xml" resource is present on the classpath).
  21. */
  22. DISABLED,
  23. /**
  24. * Switches on AspectJ load-time weaving if a "META-INF/aop.xml" resource
  25. * is present in the classpath. If there is no such resource, then AspectJ
  26. * load-time weaving will be switched off.
  27. */
  28. AUTODETECT;
  29. }
  30. }
  • 作用:用于切换不同场景实现增强。
  • 属性:
    • aspectjWeaving:是否开启LTW的支持。
      • ENABLED:开启。
      • DISABLED:不开启。
      • AUTODETECT:如果类路径下能读取到META-INF/aop.xml文件,则开启LTW,否则关闭。
  • 使用场景:

    • 在Java语言中,从织入切面的方式来看,存在是三种织入方式:编译期织入、类加载期织入和运行期织入。编译期织入是指在Java编译期,采用特殊的编译器,将切面织入到Java类中。而类加载期织入则指通过特殊的类加载器,在类字节码加载到JVM时,织入切面;运行期织入则是采用CGLIB或JDK动态代理进行切面的织入。
    • AspectJ提供了两种切面织入方式,第一种通过特殊编译器,在编译期,将AspectJ语言编写的切面类织入到Java类中,可以通过一个Ant或Maven任务来完成这个操作;第二种方式是类加载期织入,也简称为LTW(Load Time Weaving)。
  • 示例:

  • 导入相关jar包的Maven坐标:
  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-instrument</artifactId>
  4. <version>5.2.8.RELEASE</version>
  5. </dependency>
  • 在META-INF下新建aop.xml
  1. <?xml version="1.0"?>
  2. <!--
  3. AspectJ load-time weaving config file to install common Spring aspects.
  4. -->
  5. <aspectj>
  6. <!--
  7. <weaver options="-showWeaveInfo"/>
  8. -->
  9. <aspects>
  10. <!-- 切面类 -->
  11. <aspect name="com.sunxiaping.spring5.utils.ProfileAspect"/>
  12. </aspects>
  13. <weaver>
  14. <!-- 指定需要进行织入操作的目标类范围 -->
  15. <include within="com.sunxiaping.spring5.service..*"/>
  16. </weaver>
  17. </aspectj>
  • 切面类ProfileAspect.java
  1. package com.sunxiaping.spring5.utils;
  2. import org.aspectj.lang.ProceedingJoinPoint;
  3. import org.aspectj.lang.annotation.Around;
  4. import org.aspectj.lang.annotation.Aspect;
  5. import org.springframework.stereotype.Component;
  6. import org.springframework.util.StopWatch;
  7. @Component
  8. @Aspect
  9. public class ProfileAspect {
  10. /**
  11. * 统计执行效率
  12. * 希望是开发环境和测试环境有,而生产环境没有
  13. *
  14. * @param proceedingJoinPoint
  15. * @return
  16. * @throws Throwable
  17. */
  18. @Around("execution(* com.sunxiaping.spring5.service.impl.*.*(..))")
  19. public Object profile(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
  20. //创建秒表对象
  21. StopWatch sw = new StopWatch(this.getClass().getSimpleName());
  22. try {
  23. //记录执行
  24. sw.start(proceedingJoinPoint.getSignature().getName());
  25. //调用切入点方法并返回
  26. Object proceed = proceedingJoinPoint.proceed();
  27. return proceed;
  28. } finally {
  29. //停止计时
  30. sw.stop();
  31. //输出
  32. System.out.println(sw.prettyPrint());
  33. }
  34. }
  35. }
  • Spring的配置类SpringConfig.java
  1. package com.sunxiaping.spring5.config;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.context.annotation.EnableLoadTimeWeaving;
  5. /**
  6. * Spring的配置类
  7. */
  8. @Configuration
  9. @ComponentScan(basePackages = "com.sunxiaping.spring5")
  10. //@EnableAspectJAutoProxy // 开启运行期的增强
  11. @EnableLoadTimeWeaving //开启类加载时期的增强
  12. public class SpringConfig {
  13. }
  • 测试:
  1. package com.sunxiaping.spring5;
  2. import com.sunxiaping.spring5.config.SpringConfig;
  3. import com.sunxiaping.spring5.domain.User;
  4. import com.sunxiaping.spring5.service.UserService;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.test.context.ContextConfiguration;
  9. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  10. import java.util.Date;
  11. import java.util.UUID;
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration(classes = SpringConfig.class)
  14. public class SpringTest {
  15. @Autowired
  16. private UserService userService;
  17. @Test
  18. public void test() {
  19. User user = new User();
  20. user.setId(UUID.randomUUID().toString());
  21. user.setUsername("张三");
  22. user.setPassword("123456");
  23. user.setBirthday(new Date());
  24. user.setGender("男");
  25. user.setMobile("110");
  26. user.setNickname("孙子");
  27. userService.saveUser(user);
  28. }
  29. }
  • 测试配置:

测试配置.png

第五章:AOP注解执行过程及核心对象的分析

5.1 执行过程分析

5.1.1 加载@EnableAspectJAutoProxy注解

加载@EnableAspectJAutoProxy注解.png

5.1.2 解析切入点表达式

  • 如果使用了@Pointcut注解,Spring在解析切入点的时候,会将其封装为Pointcut接口的实现类。
  • Pointcut接口的源码:
  1. public interface Pointcut {
  2. /**
  3. * @return the declared name of the pointcut.
  4. */
  5. String getName();
  6. /**
  7. * @return the modifiers associated with the pointcut declaration.
  8. * Use java.lang.reflect.Modifier to interpret the return value
  9. */
  10. int getModifiers();
  11. /**
  12. * @return the pointcut parameter types.
  13. */
  14. AjType<?>[] getParameterTypes();
  15. /**
  16. * @return the pointcut parameter names. Returns an array of empty strings
  17. * of length getParameterTypes().length if parameter names are not
  18. * available at runtime.
  19. */
  20. String[] getParameterNames();
  21. /**
  22. * @return the type that declared this pointcut
  23. */
  24. AjType getDeclaringType();
  25. /**
  26. * @return the pointcut expression associated with this pointcut.
  27. */
  28. PointcutExpression getPointcutExpression();
  29. }
  • PointcutImpl的源码:
  1. public class PointcutImpl implements Pointcut {
  2. private final String name;
  3. private final PointcutExpression pc;
  4. private final Method baseMethod;
  5. private final AjType declaringType;
  6. private String[] parameterNames = new String[0];
  7. protected PointcutImpl(String name, String pc, Method method, AjType declaringType, String pNames) {
  8. this.name = name;
  9. this.pc = new PointcutExpressionImpl(pc);
  10. this.baseMethod = method;
  11. this.declaringType = declaringType;
  12. this.parameterNames = splitOnComma(pNames);
  13. }
  14. /* (non-Javadoc)
  15. * @see org.aspectj.lang.reflect.Pointcut#getPointcutExpression()
  16. */
  17. public PointcutExpression getPointcutExpression() {
  18. return pc;
  19. }
  20. public String getName() {
  21. return name;
  22. }
  23. public int getModifiers() {
  24. return baseMethod.getModifiers();
  25. }
  26. public AjType<?>[] getParameterTypes() {
  27. Class<?>[] baseParamTypes = baseMethod.getParameterTypes();
  28. AjType<?>[] ajParamTypes = new AjType<?>[baseParamTypes.length];
  29. for (int i = 0; i < ajParamTypes.length; i++) {
  30. ajParamTypes[i] = AjTypeSystem.getAjType(baseParamTypes[i]);
  31. }
  32. return ajParamTypes;
  33. }
  34. public AjType getDeclaringType() {
  35. return declaringType;
  36. }
  37. public String[] getParameterNames() {
  38. return parameterNames;
  39. }
  40. private String[] splitOnComma(String s) {
  41. StringTokenizer strTok = new StringTokenizer(s,",");
  42. String[] ret = new String[strTok.countTokens()];
  43. for (int i = 0; i < ret.length; i++) {
  44. ret[i] = strTok.nextToken().trim();
  45. }
  46. return ret;
  47. }
  48. public String toString() {
  49. StringBuffer sb = new StringBuffer();
  50. sb.append(getName());
  51. sb.append("(");
  52. AjType<?>[] ptypes = getParameterTypes();
  53. for (int i = 0; i < ptypes.length; i++) {
  54. sb.append(ptypes[i].getName());
  55. if (this.parameterNames != null && this.parameterNames[i] != null) {
  56. sb.append(" ");
  57. sb.append(this.parameterNames[i]);
  58. }
  59. if (i+1 < ptypes.length) sb.append(",");
  60. }
  61. sb.append(") : ");
  62. sb.append(getPointcutExpression().asString());
  63. return sb.toString();
  64. }
  65. }
  • 如果没有使用@Pointcut注解,Spring在解析切入点表达式的时候,会将其封装为KindedPointcut。
  • KindedPointcut的源码:
  1. public class KindedPointcut extends Pointcut {
  2. Shadow.Kind kind;
  3. private SignaturePattern signature;
  4. private int matchKinds;
  5. private ShadowMunger munger = null; // only set after concretization
  6. public KindedPointcut(Shadow.Kind kind, SignaturePattern signature) {
  7. this.kind = kind;
  8. this.signature = signature;
  9. this.pointcutKind = KINDED;
  10. this.matchKinds = kind.bit;
  11. }
  12. public KindedPointcut(Shadow.Kind kind, SignaturePattern signature, ShadowMunger munger) {
  13. this(kind, signature);
  14. this.munger = munger;
  15. }
  16. public SignaturePattern getSignature() {
  17. return signature;
  18. }
  19. //其他略
  20. }

5.2 AnnotationAwareAspectJAutoProxyCreator对象的分析

5.2.1 AnnotationAwareAspectJAutoProxyCreator的类图

AnnotationAwareAspectJAutoProxyCreator.png

5.2.2 加载过程

5.2.2.1 执行父类AbstractAutoProxyCreator的postProcessBeforeInstantiation()方法

  • AbstractAutoProxyCreator的部分源码:
  1. @Override
  2. public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
  3. if (bean != null) {
  4. //首先根据Bean的class和name构建出key
  5. Object cacheKey = getCacheKey(bean.getClass(), beanName);
  6. //判断是否需要创建指定的Bean
  7. if (this.earlyProxyReferences.remove(cacheKey) != bean) {
  8. return wrapIfNecessary(bean, beanName, cacheKey);
  9. }
  10. }
  11. return bean;
  12. }

5.2.2.2 判断是否需要增强或者已经被增强过了

  • AbstractAutoProxyCreator的部分源码:
  1. protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
  2. //如果已经处理过了
  3. if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
  4. return bean;
  5. }
  6. //如果不需要进行AOP增强
  7. if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) {
  8. return bean;
  9. }
  10. //判断这个Bean是不是基础设施类,或者配置了跳过自动大代理
  11. if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
  12. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  13. return bean;
  14. }
  15. // Create proxy if we have advice.
  16. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
  17. if (specificInterceptors != DO_NOT_PROXY) {
  18. this.advisedBeans.put(cacheKey, Boolean.TRUE);
  19. Object proxy = createProxy(
  20. bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
  21. this.proxyTypes.put(cacheKey, proxy.getClass());
  22. return proxy;
  23. }
  24. this.advisedBeans.put(cacheKey, Boolean.FALSE);
  25. return bean;
  26. }

5.2.2.3 判断是否为基础类(通知类)

  • AbstractAutoProxyCreator的部分源码:
  1. //判断是否为基础设施类,基础设施类不需要代理
  2. protected boolean isInfrastructureClass(Class<?> beanClass) {
  3. boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
  4. Pointcut.class.isAssignableFrom(beanClass) ||
  5. Advisor.class.isAssignableFrom(beanClass) ||
  6. AopInfrastructureBean.class.isAssignableFrom(beanClass);
  7. if (retVal && logger.isTraceEnabled()) {
  8. logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
  9. }
  10. return retVal;
  11. }

5.2.2.4 获取增强的代码

  • AbstractAutoProxyCreator的部分源码:
  1. @Override
  2. @Nullable
  3. protected Object[] getAdvicesAndAdvisorsForBean(
  4. Class<?> beanClass, String beanName, @Nullable TargetSource targetSource) {
  5. List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
  6. if (advisors.isEmpty()) {
  7. return DO_NOT_PROXY;
  8. }
  9. return advisors.toArray();
  10. }

5.2.2.5 根据增强创建代理对象

  • AbstractAutoProxyCreator的部分源码:
  1. protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
  2. @Nullable Object[] specificInterceptors, TargetSource targetSource) {
  3. if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
  4. AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
  5. }
  6. ProxyFactory proxyFactory = new ProxyFactory();
  7. proxyFactory.copyFrom(this);
  8. if (!proxyFactory.isProxyTargetClass()) {
  9. if (shouldProxyTargetClass(beanClass, beanName)) {
  10. proxyFactory.setProxyTargetClass(true);
  11. }
  12. else {
  13. evaluateProxyInterfaces(beanClass, proxyFactory);
  14. }
  15. }
  16. Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
  17. proxyFactory.addAdvisors(advisors);
  18. proxyFactory.setTargetSource(targetSource);
  19. customizeProxyFactory(proxyFactory);
  20. proxyFactory.setFrozen(this.freezeProxy);
  21. if (advisorsPreFiltered()) {
  22. proxyFactory.setPreFiltered(true);
  23. }
  24. return proxyFactory.getProxy(getProxyClassLoader());
  25. }