Spring及Spring Boot注入依赖的Bean

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37793798/article/details/83304008

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 PropertyPlaceholderConfigurer conf = new PropertyPlaceholderConfigurer();
		final List<Resource> resources = new ArrayList<>();
		resources.add(new ClassPathResource("third-party-application.properties"));
		conf.setLocations(resources.toArray(new Resource[]{}));
		return conf;
	}
}

方法二:定义PropertyPlaceholderConfigurer的Bean

@Bean
public class PropertyConfigurer extends PropertyPlaceholderConfigurer {
	public PropertyConfigurer() {
		this.setIgnoreResourceNotFound(true);
		final List<Resource> resources = new ArrayList<>();
		resources.add(new ClassPathResource("third-party-application.properties"));
		this.setLocations(resources.toArray(new Resource[]{}));
	}
}

方法三:使用@ConfigurationProperties

详见Spring Boot文档

方法四:命令行运行时使用spring.config.location环境属性指定特定的properties文件

详见Spring Boot文档中Externalized Configuration相关内容

潜在的坑

  • Jar包依赖没有添加到Pom,或者没有mvn install到本地环境
  • <context:property-placeholder/>和PropertyPlaceholderConfigurer的冲突问题
  • 始终无法获取properties文件的配置,请阅读参考阅读#2链接

参考阅读


  1. Spring Boot读取外部配置 ↩︎

猜你喜欢

转载自blog.csdn.net/m0_37793798/article/details/83304008