【框架】Spring及Spring Boot注入依賴的Bean

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讀取外部配置 ↩︎

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章