开心一刻

    一只被二哈带偏了的柴犬,我只想弄死隔壁的二哈

  BeanFactoryPostProcessor接口很简单,只包含一个方法

  1. /**
  2. * 通过BeanFactoryPostProcessor,我们自定义修改应用程序上下文中的bean定义
  3. *
  4. * 应用上下文能够在所有的bean定义中自动检测出BeanFactoryPostProcessor bean,
  5. * 并在任何其他bean创建之前应用这些BeanFactoryPostProcessor bean
  6. *
  7. * BeanFactoryPostProcessor对自定义配置文件非常有用,可以覆盖应用上下文已经配置了的bean属性
  8. *
  9. * PropertyResourceConfigurer就是BeanFactoryPostProcessor的典型应用
  10. * 将xml文件中的占位符替换成properties文件中相应的key对应的value
  11. */
  12. @FunctionalInterface
  13. public interface BeanFactoryPostProcessor {
  14. /**
  15. * 在应用上下文完成了标准的初始化之后,修改其内部的bean工厂
  16. * 将加载所有bean定义,但尚未实例化任何bean.
  17. * 我们可以覆盖或添加bean定义中的属性,甚至是提前初始化bean
  18. */
  19. void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
  20. }

  推荐大家直接去读它的源码注释,说的更详细、更好理解

  简单来说,BeanFactoryPostProcessor是spring对外提供的接口,用来拓展spring,能够在spring容器加载了所有bean的信息信息之后、bean实例化之前执行,修改bean的定义属性;有人可能会问,这有什么用?大家还记得spring配置文件中的占位符吗? 我们会在spring配置中配置PropertyPlaceholderConfigurer(继承PropertyResourceConfigurer)bean来处理占位符, 举个例子大家就有印象了

  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" xmlns:context="http://www.springframework.org/schema/context"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context
  7. http://www.springframework.org/schema/context/spring-context.xsd
  8.  
  9. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  10. <property name="locations">
  11. <list>
  12. <value>classpath:mysqldb.properties</value>
  13. </list>
  14. </property>
  15. </bean>
  16.  
  17. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
  18. <property name="driverClassName"value="${jdbc.driverClassName}" />
  19. <property name="url" value="${jdbc.url}" />
  20. <property name="username" value="${jdbc.username}"/>
  21. <property name="password"value="${jdbc.password}" />
  22. </bean>
  23. </beans>

  mysqldb.properties

  1. jdbc.driverClassName=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://192.168.1.100:3306/mybatis
  3. jdbc.username=root
  4. jdbc.password=root

  PropertyPlaceholderConfigurer类的继承关系图

  怎么用,这个问题比较简单,我们实现BeanFactoryPostProcessor接口,然后将将其注册到spring容器即可,在spring启动过程中,在常规bean实例化之前,会执行BeanFactoryPostProcessor的postProcessBeanFactory方法(里面有我们想要的逻辑),完成我们想要的操作;

  重点应该是:用来干什么

  上述占位符的例子是BeanFactoryPostProcessor的应用之一,但这是spring提供的BeanFactoryPostProcessor拓展,不是我们自定义的;实际工作中,自定义BeanFactoryPostProcessor的情况确实少,反正至少我是用的非常少的,但我还是有使用印象的,那就是对敏感信息的解密处理;上述数据库的连接配置中,用户名和密码都是明文配置的,这就存在泄漏风险,还有redis的连接配置、shiro的加密算法、rabbitmq的连接配置等等,凡是涉及到敏感信息的,都需要进行加密处理,信息安全非常重要

  配置的时候以密文配置,在真正用到之前在spring容器中进行解密,然后用解密后的信息进行真正的操作,下面我就举个简单的例子,用BeanFactoryPostProcessor来完整敏感信息的解密

  加解密工具类:DecryptUtil.java

  1. package com.lee.app.util;
  2. import org.apache.commons.lang3.StringUtils;
  3. import sun.misc.BASE64Decoder;
  4. import sun.misc.BASE64Encoder;
  5. import javax.crypto.Cipher;
  6. import javax.crypto.KeyGenerator;
  7. import java.security.Key;
  8. import java.security.SecureRandom;
  9. public class DecryptUtil {
  10. private static final String CHARSET = "utf-8";
  11. private static final String ALGORITHM = "AES";
  12. private static final String RANDOM_ALGORITHM = "SHA1PRNG";
  13. public static String aesEncrypt(String content, String key) {
  14. if (content == null || key == null) {
  15. return null;
  16. }
  17. Key secretKey = getKey(key);
  18. try {
  19. Cipher cipher = Cipher.getInstance(ALGORITHM);
  20. cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  21. byte[] p = content.getBytes(CHARSET);
  22. byte[] result = cipher.doFinal(p);
  23. BASE64Encoder encoder = new BASE64Encoder();
  24. String encoded = encoder.encode(result);
  25. return encoded;
  26. } catch (Exception e) {
  27. throw new RuntimeException(e);
  28. }
  29. }
  30. public static String aesDecrypt(String content, String key) {
  31. Key secretKey = getKey(key);
  32. try {
  33. Cipher cipher = Cipher.getInstance(ALGORITHM);
  34. cipher.init(Cipher.DECRYPT_MODE, secretKey);
  35. BASE64Decoder decoder = new BASE64Decoder();
  36. byte[] c = decoder.decodeBuffer(content);
  37. byte[] result = cipher.doFinal(c);
  38. String plainText = new String(result, CHARSET);
  39. return plainText;
  40. } catch (Exception e) {
  41. throw new RuntimeException(e);
  42. }
  43. }
  44. private static Key getKey(String key) {
  45. if (StringUtils.isEmpty(key)) {
  46. key = "hello!@#$world";// 默认key
  47. }
  48. try {
  49. SecureRandom secureRandom = SecureRandom.getInstance(RANDOM_ALGORITHM);
  50. secureRandom.setSeed(key.getBytes());
  51. KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
  52. generator.init(secureRandom);
  53. return generator.generateKey();
  54. } catch (Exception e) {
  55. throw new RuntimeException(e);
  56. }
  57. }
  58. public static void main(String[] args) {
  59. // key可以随意取,DecryptConfig中decryptKey与此相同即可
  60. String newUserName= aesEncrypt("root", "hello!@#$world"); // QL34YffNntJi1OWG7zGqVw==
  61. System.out.println(newUserName);
  62. String originUserName = aesDecrypt(newUserName, "hello!@#$world");
  63. System.out.println(originUserName);
  64. String newPassword = aesEncrypt("123456", "hello!@#$world"); // zfF/EU6k4YtzTnKVZ6xddw==
  65. System.out.println(newPassword);
  66. String orignPassword = aesDecrypt(newPassword, "hello!@#$world");
  67. System.out.println(orignPassword);
  68. }
  69. }

View Code

  配置文件:application.yml

  1. server:
  2. servlet:
  3. context-path: /app
  4. port: 8888
  5. spring:
  6. #连接池配置
  7. datasource:
  8. type: com.alibaba.druid.pool.DruidDataSource
  9. druid:
  10. driver-class-name: com.mysql.jdbc.Driver
  11. url: jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf-8
  12. #Enc[:解密标志前缀,]:解密后缀标志,中间内容是需要解密的内容
  13. username: Enc[QL34YffNntJi1OWG7zGqVw==]
  14. password: Enc[zfF/EU6k4YtzTnKVZ6xddw==]
  15. initial-size: 1 #连接池初始大小
  16. max-active: 20 #连接池中最大的活跃连接数
  17. min-idle: 1 #连接池中最小的活跃连接数
  18. max-wait: 60000 #配置获取连接等待超时的时间
  19. pool-prepared-statements: true #打开PSCache,并且指定每个连接上PSCache的大小
  20. max-pool-prepared-statement-per-connection-size: 20
  21. validation-query: SELECT 1 FROM DUAL
  22. validation-query-timeout: 30000
  23. test-on-borrow: false #是否在获得连接后检测其可用性
  24. test-on-return: false #是否在连接放回连接池后检测其可用性
  25. test-while-idle: true #是否在连接空闲一段时间后检测其可用性
  26. #mybatis配置
  27. mybatis:
  28. type-aliases-package: com.lee.app.entity
  29. #config-location: classpath:mybatis/mybatis-config.xml
  30. mapper-locations: classpath:mapper/*.xml
  31. # pagehelper配置
  32. pagehelper:
  33. helperDialect: mysql
  34. #分页合理化,pageNum<=0则查询第一页的记录;pageNum大于总页数,则查询最后一页的记录
  35. reasonable: true
  36. supportMethodsArguments: true
  37. params: count=countSql
  38. decrypt:
  39. prefix: "Enc["
  40. suffix: "]"
  41. key: "hello!@#$world"

View Code

  工程中解密:DecryptConfig.java

  1. package com.lee.app.config;
  2. import com.lee.app.util.DecryptUtil;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.BeansException;
  6. import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
  7. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  8. import org.springframework.boot.env.OriginTrackedMapPropertySource;
  9. import org.springframework.context.EnvironmentAware;
  10. import org.springframework.core.env.ConfigurableEnvironment;
  11. import org.springframework.core.env.Environment;
  12. import org.springframework.core.env.MutablePropertySources;
  13. import org.springframework.core.env.PropertySource;
  14. import org.springframework.stereotype.Component;
  15. import java.util.LinkedHashMap;
  16. import java.util.stream.Collectors;
  17. import java.util.stream.StreamSupport;
  18. /**
  19. * 敏感信息的解密
  20. */
  21. @Component
  22. public class DecryptConfig implements EnvironmentAware, BeanFactoryPostProcessor {
  23. private static final Logger LOGGER = LoggerFactory.getLogger(DecryptConfig.class);
  24. private ConfigurableEnvironment environment;
  25. private String decryptPrefix = "Enc["; // 解密前缀标志 默认值
  26. private String decryptSuffix = "]"; // 解密后缀标志 默认值
  27. private String decryptKey = "hello!@#$world"; // 解密可以 默认值
  28. @Override
  29. public void setEnvironment(Environment environment) {
  30. this.environment = (ConfigurableEnvironment) environment;
  31. }
  32. @Override
  33. public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  34. LOGGER.info("敏感信息解密开始.....");
  35. MutablePropertySources propSources = environment.getPropertySources();
  36. StreamSupport.stream(propSources.spliterator(), false)
  37. .filter(ps -> ps instanceof OriginTrackedMapPropertySource)
  38. .collect(Collectors.toList())
  39. .forEach(ps -> convertPropertySource((PropertySource<LinkedHashMap>) ps));
  40. LOGGER.info("敏感信息解密完成.....");
  41. }
  42. /**
  43. * 解密相关属性
  44. * @param ps
  45. */
  46. private void convertPropertySource(PropertySource<LinkedHashMap> ps) {
  47. LinkedHashMap source = ps.getSource();
  48. setDecryptProperties(source);
  49. source.forEach((k,v) -> {
  50. String value = String.valueOf(v);
  51. if (!value.startsWith(decryptPrefix) || !value.endsWith(decryptSuffix)) {
  52. return;
  53. }
  54. String cipherText = value.replace(decryptPrefix, "").replace(decryptSuffix, "");
  55. String clearText = DecryptUtil.aesDecrypt(cipherText, decryptKey);
  56. source.put(k, clearText);
  57. });
  58. }
  59. /**
  60. * 设置解密属性
  61. * @param source
  62. */
  63. private void setDecryptProperties(LinkedHashMap source) {
  64. decryptPrefix = source.get("decrypt.prefix") == null ? decryptPrefix : String.valueOf(source.get("decrypt.prefix"));
  65. decryptSuffix = source.get("decrypt.suffix") == null ? decryptSuffix : String.valueOf(source.get("decrypt.suffix"));
  66. decryptKey = source.get("decrypt.key") == null ? decryptKey : String.valueOf(source.get("decrypt.key"));
  67. }
  68. }

View Code

  主要就是3个文件,DecryptUtil对明文进行加密处理后,得到的值配置到application.yml中,然后工程启动的时候,DecryptConfig会对密文进行解密,明文信息存到了spring容器,后续操作都是在spring容器的明文上进行的,所以与我们平时的不加密的结果一致,但是却对敏感信息进行了保护;工程测试结果如下:

  完整工程地址:spring-boot-BeanFactoryPostProcessor

  有兴趣的可以去看下jasypt-spring-boot的源码,你会发现他的原理是一样的,也是基于BeanFactoryPostProcessor的拓展

  为什么DecryptConfig实现了BeanFactoryPostProcessor,将DecryptConfig注册到spring之后,DecryptConfig的postProcessBeanFactory方法就会执行?事出必有因,肯定是spring启动过程中会调用DecryptConfig实例的postProcessBeanFactory方法,具体我们来看看源码,我们从AbstractApplicationContext的refresh方法开始

  不得不说,spring的命名、注释确实写得好,很明显我们从refresh中的invokeBeanFactoryPostProcessors方法开始,大家可以仔细看下PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors方法,先按PriorityOrdered、Ordered、普通(没有实现PriorityOrdered和Ordered接口)的顺序调用BeanDefinitionRegistryPostProcessor,然后再按先按PriorityOrdered、Ordered、普通的顺序调用BeanFactoryPostProcessor,这个顺序还是值得大家注意下的,如果我们自定义的多个BeanFactoryPostProcessor有顺序之分,而我们又没有指定其执行顺序,那么可能出现的不是我们想要的结果

  这里可能会有会有人有这样的的疑问:bean定义(BeanDefinition)是在什么时候加载到spring容器的,如何保证BeanFactoryPostProcessor实例起作用之前,所有的bean定义都已经加载到了spring容器

    ConfigurationClassPostProcessor实现了BeanDefinitionRegistryPostProcessor,在springboot的createApplicationContext阶段注册到spring容器的,也就是说在spring的refresh之前就有了ConfigurationClassPostProcessor实例;ConfigurationClassPostProcessor被应用的时候(调用其postProcessBeanDefinitionRegistry方法),会加载全部的bean定义(包括我们自定义的BeanFactoryPostProcessor实例:DecryptConfig)到spring容器,bean的加载详情可查看:springboot2.0.3源码篇 – 自动配置的实现,是你想象中的那样吗,那么在应用BeanFactoryPostProcessor实例之前,所有的bean定义就已经加载到spring容器了,BeanFactoryPostProcessor实例也就能修改bean定义了

  至此,BeanFactoryPostProcessor的机制我们就清楚了,为什么能这么用这个问题也就明了了

  1、BeanFactoryPostProcessor是beanFactory的后置处理器接口,通过BeanFactoryPostProcessor,我们可以自定义spring容器中的bean定义,BeanFactoryPostProcessor是在spring容器加载了bean的定义信息之后、bean实例化之前执行;

  2、BeanFactoryPostProcessor类型的bean会被spring自动检测,在常规bean实例化之前被spring调用;

  3、BeanFactoryPostProcessor的常用场景包括spring中占位符的处理、我们自定义的敏感信息的解密处理,当然不局限与此;

  其实只要我们明白了BeanFactoryPostProcessor的生效时机,哪些场景适用BeanFactoryPostProcessor也就很清楚了

版权声明:本文为youzhibing原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/youzhibing/p/10559337.html