2018-10-23 某模型平台需要注入子模块的Bean
文章目录
前言
模块化的Spring或Spring Boot工程,当遇到某个模块是基础工具模块或者模块间代码依赖较复杂的情况,其它模块就需要注入所依赖模块的Bean。
Spring导入依赖的Bean
假设第三jar包中采用的是XML配置文件(third-party-appContext.xml),则可直接使用如下方法导入依赖的Bean:
<import resource="classpath:third-party-appContext.xml"/>
为保证jar包的配置文件能被正确获取,在third-party-appContext.xml中配置好PropertyPlaceholderConfigurer
的Bean即可。
Spring Boot导入依赖的Bean
Spring Boot与Spring在这个问题上的最大的区别是:Spring Boot对配置文件命名是有约束的,默认情况下它只会读取特定目录下名为application.properties
的配置文件1。而Spring Boot本身会自动生成一个PropertyPlaceholderConfigurer
的Bean去获取application.properties
,所以如果在XML中配置该Bean是不会生效的。
方法一:定义配置类覆盖PropertyPlaceholderConfigurer
@Configuration
public class PropertyConfigurer {
@Bean
public static PropertyPlaceholderConfigurer properties() {
final PropertyPlaceholderConfigure