SpringBoot如何让业务Bean优先于其他Bean加载

打印 上一主题 下一主题

主题 907|帖子 907|积分 2721

本博客原文地址:https://ntopic.cn/p/2023090901/
源代码先行:
背景介绍

今天走读一个应用程序代码,发现一个有趣的现象:有多个不同的业务Bean中均依赖了一个参数工具类ParamUtils(即:@Autowired ParamUtils paramUtis),ParamUtils依赖了ParamDAO Bean用于从DB中获取参数;为了便于ParamUtils使用,工具类全部都是static静态方法,也就是说,业务Bean仅仅增加Autowired依赖,在实际调用时还是直接使用的ParamUtils类静态方法。那个Autowired注入ParamUtils的依赖看起来是无用代码,但是其实还不能去掉。
代码业务这么写的目的其实很好理解:因为ParamUtils依赖了DAO Bean,增加依赖是保障ParamUtils的类静态方法在调用时已经被SpringBoot初始化了。那么,有没有更优雅的办法,能让业务代码更优雅更安全的使用ParamUtils工具类呢?
思路分析

ParamUtils业务Bean,比其他的业务Bean提前初始化,基本思路如下:
第一思路:采用优先级Ordered注解(类:org.springframework.core.Ordered),但是不可行,因为该注解主要是用于控制Spring自身Bean的初始化顺序,如Listener/Filter等。
第二思路:采用Bean依赖DependsOn注解(类:org.springframework.context.annotation.DependsOn),该方法可行,它和Autowired注解一致,也是表明Bean之间依赖,但是没有从本质上解决问题。
第三思路:手工注册Bean让Spring优先初始化,查看SpringApplication类代码,发现里面有个addInitializers(ApplicationContextInitializer... initializers)方法,可以让业务在ApplicationContext初始化时initialize(C applicationContext)基于Context做一些事情。那么可不可以在这个地方,能手工注册业务Bean呢?
代码实现和验证

代码分为3部分:ParamDAO业务Bean访问DB,ParamUtils参数工具类依赖ParamDAO,RestController测试类使用参数工具类。
为了阅读方便,以下展示的代码均只有主体部分,完整的代码注释和代码内容,请下载本工程仓库。
ParamDAO业务Bean

为了测试简便,本工程不依赖MySQL数据库,我们还是采用SQLite,源文件就在代码根目录下,clone本仓库后即可执行运行:
SQLite数据表准备

首先新建一张参数表(nt_param),并且插入一些数据。为了尽快验证我们的思路,其他的数据新增、修改和删除等就不做特别的验证了。
  1. --
  2. -- 参数表
  3. --
  4. CREATE TABLE nt_param
  5. (
  6.     id          bigint unsigned NOT NULL auto_increment,
  7.     category    varchar(64) NOT NULL,
  8.     module      varchar(64) NOT NULL,
  9.     name        varchar(64) NOT NULL,
  10.     content     varchar(4096) DEFAULT '',
  11.     create_time timestamp,
  12.     modify_time timestamp,
  13.     PRIMARY KEY (id),
  14.     UNIQUE (category, module, name)
  15. );
  16. --
  17. -- 插入数据
  18. --
  19. INSERT INTO nt_param (category, module, name, content, create_time, modify_time)
  20. VALUES ('CONFIG', 'USER', 'minAge', '18', strftime('%Y-%m-%d %H:%M:%f', 'now'), strftime('%Y-%m-%d %H:%M:%f', 'now')),
  21.        ('CONFIG', 'USER', 'maxAge', '60', strftime('%Y-%m-%d %H:%M:%f', 'now'), strftime('%Y-%m-%d %H:%M:%f', 'now'));
复制代码
ParamDAO数据查询

NTParamDAO为普通的Spring Bean(ID为:ntParamDAO)
  1. @Repository("ntParamDAO")
  2. public interface NTParamDAO {
  3.     @Select("SELECT * FROM nt_param WHERE category=#{category,jdbcType=VARCHAR} AND module=#{module,jdbcType=VARCHAR}")
  4.     List<NTParamDO> selectByModule(@Param("category") String category, @Param("module") String module);
  5. }
复制代码
ParamUtils工具类定义和使用

ParamUtils工具类定义:非Spring Bean

ParamUtils是静态工具类,依赖了ParamDAO Spring Bean,并且ParamUtils并不是Spring Bean:
  1. // @Component("ntParamUtils") SpringBoot优先初始化本类,因此无需增加注解
  2. public class NTParamUtils {
  3.     private static final Logger LOGGER = LoggerFactory.getLogger(LogConstants.DAS);
  4.     /**
  5.      * 系统参数DAO
  6.      */
  7.     private static NTParamDAO NT_PARAM_DAO;
  8.     /**
  9.      * 依赖注入
  10.      */
  11.     public NTParamUtils(@Qualifier("ntParamDAO") NTParamDAO ntParamDAO) {
  12.         Assert.notNull(ntParamDAO, "NTParamDAO注入为NULL.");
  13.         NT_PARAM_DAO = ntParamDAO;
  14.         // 打印日志
  15.         LOGGER.info("{}:初始化完成.", this.getClass().getName());
  16.     }
  17.     public static List<NTParamDO> findList(String category, String module) {
  18.         Assert.hasText(category, "分类参数为空");
  19.         Assert.hasText(module, "模块参数为空");
  20.         return NT_PARAM_DAO.selectByModule(category, module);
  21.     }
  22. }
复制代码
ParamUtils工具类使用:普通Spring Bean

NTUserServiceImpl是一个普通的Spring Bean,它没有显示依赖ParamUtils,而是直接使用它:
  1. @Component("ntUserService")
  2. public final class NTUserServiceImpl implements NTUserService {
  3.     private static final Logger LOGGER = LoggerFactory.getLogger(LogConstants.BIZ);
  4.     @Autowired
  5.     public NTUserServiceImpl() {
  6.         // 打印日志
  7.         LOGGER.info("{}:初始化完成.", this.getClass().getName());
  8.     }
  9.     /**
  10.      * 获取用户模块参数
  11.      */
  12.     @Override
  13.     public List<NTParamDO> findUserParamList() {
  14.         return NTParamUtils.findList("CONFIG", "USER");
  15.     }
  16. }
复制代码
SpringBoot优先初始化设置

两个关键点:

  • ApplicationContextInitializer类:提供Context初始化入口,业务逻辑可以通过此次注入。
  • BeanDefinitionRegistryPostProcessor类:Spring Bean收集完成后,但还没有初始化之前入口,我们的关键就在这里定义ParamUtils Bean,并且Bean定义为RootBeanDefinition保障提前初始化。
Context自定义初始化:手工注册ParamUtils Bean
  1. public class NTApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>, BeanDefinitionRegistryPostProcessor {
  2.    
  3.     /**
  4.      * Context初始化,给业务逻辑初始化提供了机会
  5.      */
  6.     @Override
  7.     public void initialize(ConfigurableApplicationContext context) {
  8.         // 注册Bean上下文初始化后处理器,用于手工注册Bean
  9.         context.addBeanFactoryPostProcessor(this);
  10.     }
  11.     /**
  12.      * 手工注册ParamUtils工具类,并且是RootBean定义,保障优先初始化,下面会详细分析
  13.      */
  14.     @Override
  15.     public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
  16.         // 在ConfigurationClassPostProcessor前手动注册Bean,保障优先于其他Bean初始化
  17.         registry.registerBeanDefinition("ntParamUtils", new RootBeanDefinition(NTParamUtils.class));
  18.     }
  19.     @Override
  20.     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  21.     }
  22. }
复制代码
SpringBoot启动类增加自定义初始化器

原来的方法:SpringApplication.run(NTBootApplication.class, args);
  1. @SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
  2. @MapperScan(basePackages = "cn.ntopic.das..**.dao", sqlSessionFactoryRef = "ntSqlSessionFactory")
  3. public class NTBootApplication {
  4.     /**
  5.      * SpringBoot启动
  6.      */
  7.     public static void main(String[] args) {
  8.         // 注册自定义处理器
  9.         SpringApplication application = new SpringApplication(NTBootApplication.class);
  10.         application.addInitializers(new NTApplicationContextInitializer());
  11.         // SpringBoot启动
  12.         application.run(args);
  13.     }
  14. }
复制代码
至此,业务Bean提前初始化的整个代码完毕,下面进行验证!
ParamUtils初始化验证(符合预期)

我们分表从SpringBoot的启动日志和实际使用2个方面来验证我们的设计思路:
SpringBoot启动日志:符合预期

从第21行和第22行日志,可以看到,ParamUtils优于其他Bean完成初始化:
  1.   .   ____          _            __ _ _
  2. /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
  3. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  4. \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  5.   '  |____| .__|_| |_|_| |_\__, | / / / /
  6. =========|_|==============|___/=/_/_/_/
  7. :: Spring Boot ::                (v2.5.3)
  8. 2023-09-09 11:40:55,607  INFO (StartupInfoLogger.java:55)- Starting NTBootApplication using Java 1.8.0_281 on OXL-MacBook.local with PID 1371 (/Users/obullxl/CodeSpace/ntopic-boot/ntopic/target/classes started by obullxl in /Users/obullxl/CodeSpace/ntopic-boot)
  9. 2023-09-09 11:40:55,612  INFO (SpringApplication.java:659)- No active profile set, falling back to default profiles: default
  10. 2023-09-09 11:40:55,692  INFO (DeferredLog.java:255)- Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
  11. 2023-09-09 11:40:55,693  INFO (DeferredLog.java:255)- For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
  12. 2023-09-09 11:40:56,834  INFO (TomcatWebServer.java:108)- Tomcat initialized with port(s): 8088 (http)
  13. 2023-09-09 11:40:56,842  INFO (DirectJDKLog.java:173)- Initializing ProtocolHandler ["http-nio-8088"]
  14. 2023-09-09 11:40:56,842  INFO (DirectJDKLog.java:173)- Starting service [Tomcat]
  15. 2023-09-09 11:40:56,842  INFO (DirectJDKLog.java:173)- Starting Servlet engine: [Apache Tomcat/9.0.50]
  16. 2023-09-09 11:40:56,901  INFO (DirectJDKLog.java:173)- Initializing Spring embedded WebApplicationContext
  17. 2023-09-09 11:40:56,901  INFO (ServletWebServerApplicationContext.java:290)- Root WebApplicationContext: initialization completed in 1208 ms
  18. 2023-09-09 11:40:57,043 ERROR (Log4j2Impl.java:58)- testWhileIdle is true, validationQuery not set
  19. 2023-09-09 11:40:57,051  INFO (Log4j2Impl.java:106)- {dataSource-1} inited
  20. 2023-09-09 11:40:57,127  INFO (NTParamUtils.java:39)- cn.ntopic.NTParamUtils:初始化完成.
  21. 2023-09-09 11:40:57,160  INFO (NTUserServiceImpl.java:78)- cn.ntopic.service.impl.NTUserServiceImpl:初始化完成.
  22. 2023-09-09 11:40:57,170  INFO (NTExecutorConfig.java:65)- start ntThreadPool
  23. 2023-09-09 11:40:57,563  INFO (OptionalLiveReloadServer.java:58)- LiveReload server is running on port 35729
  24. 2023-09-09 11:40:57,582  INFO (DirectJDKLog.java:173)- Starting ProtocolHandler ["http-nio-8088"]
  25. 2023-09-09 11:40:57,600  INFO (TomcatWebServer.java:220)- Tomcat started on port(s): 8088 (http) with context path ''
  26. 2023-09-09 11:40:57,610  INFO (StartupInfoLogger.java:61)- Started NTBootApplication in 2.363 seconds (JVM running for 3.091)
复制代码
RestController验证:符合预期
  1. @RestController
  2. public class NTParamAct {
  3.     private final NTUserService ntUserService;
  4.     public NTParamAct(@Qualifier("ntUserService") NTUserService ntUserService) {
  5.         this.ntUserService = ntUserService;
  6.     }
  7.     @RequestMapping("/param")
  8.     public List<NTParamDO> paramList() {
  9.         return this.ntUserService.findUserParamList();
  10.     }
  11. }
复制代码
打开浏览器,访问:http://localhost:8088/param
可以看到,参数数据被查询并输出:
  1. [
  2.     {
  3.         "id": 3,
  4.         "category": "CONFIG",
  5.         "module": "USER",
  6.         "name": "maxAge",
  7.         "content": "60",
  8.         "createTime": "2023-09-08T18:30:20.818+00:00",
  9.         "modifyTime": "2023-09-08T18:30:20.818+00:00"
  10.     },
  11.     {
  12.         "id": 2,
  13.         "category": "CONFIG",
  14.         "module": "USER",
  15.         "name": "minAge",
  16.         "content": "18",
  17.         "createTime": "2023-09-08T18:30:20.818+00:00",
  18.         "modifyTime": "2023-09-08T18:30:20.818+00:00"
  19.     }
  20. ]
复制代码
SpringBoot实现分析

SpringBoot启动的代码入口:
  1. public static void main(String[] args) {
  2.     // 注册自定义处理器
  3.     SpringApplication application = new SpringApplication(NTBootApplication.class);
  4.     application.addInitializers(new NTApplicationContextInitializer());
  5.     // SpringBoot启动
  6.     application.run(args);
  7. }
复制代码
有几个非常核心的点,基本调用链路:

  • SpringApplication类:run() -> prepareContext() -> applyInitializers(本方法:调用自定义NTApplicationContextInitializer上下文器)
  • SpringApplication类:run() -> refreshContext() -> refresh(ConfigurableApplicationContext)
  • ConfigurableApplicationContext类:AbstractApplicationContext.refresh() -> finishBeanFactoryInitialization(ConfigurableListableBeanFactory)
  • ConfigurableListableBeanFactory类,关键代码都在这里:preInstantiateSingletons()


  • beanDefinitionNames属性:Spring收集到的所有Bean定义,包括Repository注解、Component注解和我们手工定义的Bean
  • 遍历beanDefinitionNames的时候,优先RootBeanDefinition初始化,手工定义的ParamUtils也是该类型
至此,问题解决,能解决的原因也搞清楚了!

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

石小疯

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表