深入 Spring Boot : 那些注入不了的 Spring 占位符(${} 表達式)

Spring里的占位符

spring里的占位符通常表現(xiàn)的形式是:

或者

@Configuration

@ImportResource("classpath:/com/acme/properties-config.xml")

public class AppConfig {

@Value("${jdbc.url}")

private String url;

}

Spring應(yīng)用在有時會出現(xiàn)占位符配置沒有注入,原因可能是多樣的。

本文介紹兩種比較復(fù)雜的情況床嫌。

占位符是在Spring生命周期的什么時候處理的

Spirng在生命周期里關(guān)于Bean的處理大概可以分為下面幾步:

加載Bean定義(從xml或者從@Import等)

處理BeanFactoryPostProcessor

實例化Bean

處理Bean的property注入

處理BeanPostProcessor

當然這只是比較理想的狀態(tài)审磁,實際上因為Spring Context在構(gòu)造時吁系,也需要創(chuàng)建很多內(nèi)部的Bean醋拧,應(yīng)用在接口實現(xiàn)里也會做自己的各種邏輯,整個流程會非常復(fù)雜筐骇。

那么占位符(${}表達式)是在什么時候被處理的惠拭?

實際上是在org.springframework.context.support.PropertySourcesPlaceholderConfigurer里處理的扩劝,它會訪問了每一個bean的BeanDefinition,然后做占位符的處理职辅;

PropertySourcesPlaceholderConfigurer實現(xiàn)了BeanFactoryPostProcessor接口棒呛;

PropertySourcesPlaceholderConfigurer的 order是Ordered.LOWEST_PRECEDENCE,也就是最低優(yōu)先級的罐农。

結(jié)合上面的Spring的生命周期条霜,如果Bean的創(chuàng)建和使用在PropertySourcesPlaceholderConfigurer之前催什,那么就有可能出現(xiàn)占位符沒有被處理的情況涵亏。

例子1:Mybatis 的 MapperScannerConfigurer引起的占位符沒有處理

例子代碼:mybatis-demo.zip

https://github.com/hengyunabc/hengyunabc.github.io/files/1158339/mybatis-demo.zip

首先應(yīng)用自己在代碼里創(chuàng)建了一個DataSource,其中${db.user}是希望從application.properties里注入的蒲凶。代碼在運行時會打印出user的實際值气筋。

@Configuration

public class MyDataSourceConfig {

@Bean(name = "dataSource1")

public DataSource dataSource1(@Value("${db.user}") String user) {

System.err.println("user: " + user);

JdbcDataSource ds = new JdbcDataSource();

ds.setURL("jdbc:h2:?/test");

ds.setUser(user);

return ds;

}

}

然后應(yīng)用用代碼的方式來初始化mybatis相關(guān)的配置,依賴上面創(chuàng)建的DataSource對象

@Configuration

public class MybatisConfig1 {

@Bean(name = "sqlSessionFactory1")

public SqlSessionFactory sqlSessionFactory1(DataSource dataSource1) throws Exception {

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

org.apache.ibatis.session.Configuration ibatisConfiguration = new org.apache.ibatis.session.Configuration();

sqlSessionFactoryBean.setConfiguration(ibatisConfiguration);

sqlSessionFactoryBean.setDataSource(dataSource1);

sqlSessionFactoryBean.setTypeAliasesPackage("sample.mybatis.domain");

return sqlSessionFactoryBean.getObject();

}

@Bean

MapperScannerConfigurer mapperScannerConfigurer(SqlSessionFactory sqlSessionFactory1) {

MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();

mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory1");

mapperScannerConfigurer.setBasePackage("sample.mybatis.mapper");

return mapperScannerConfigurer;

}

}

當代碼運行時旋圆,輸出結(jié)果是:

user: ${db.user}

為什么會user這個變量沒有被注入宠默?

分析下Bean定義,可以發(fā)現(xiàn)MapperScannerConfigurer它實現(xiàn)了BeanDefinitionRegistryPostProcessor灵巧。這個接口在是Spring掃描Bean定義時會回調(diào)的搀矫,遠早于BeanFactoryPostProcessor。

所以原因是:

MapperScannerConfigurer它實現(xiàn)了BeanDefinitionRegistryPostProcessor刻肄,所以它會Spring的早期會被創(chuàng)建瓤球;

從bean的依賴關(guān)系來看,mapperScannerConfigurer依賴了sqlSessionFactory1敏弃,sqlSessionFactory1依賴了dataSource1卦羡;

MyDataSourceConfig里的dataSource1被提前初始化,沒有經(jīng)過PropertySourcesPlaceholderConfigurer的處理,所以@Value(“${db.user}”) String user 里的占位符沒有被處理绿饵。

要解決這個問題欠肾,可以在代碼里,顯式來處理占位符:

environment.resolvePlaceholders("${db.user}")

例子2:Spring boot自身實現(xiàn)問題拟赊,導(dǎo)致Bean被提前初始化

例子代碼:demo.zip

https://github.com/spring-projects/spring-boot/files/773587/demo.zip

Spring Boot里提供了@ConditionalOnBean刺桃,這個方便用戶在不同條件下來創(chuàng)建bean。里面提供了判斷是否存在bean上有某個注解的功能吸祟。

@Target({ ElementType.TYPE, ElementType.METHOD })

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Conditional(OnBeanCondition.class)

public @interface ConditionalOnBean {

/**

* The annotation type decorating a bean that should be checked. The condition matches

* when any of the annotations specified is defined on a bean in the

* {@link ApplicationContext}.

* @return the class-level annotation types to check

*/

Class[] annotation() default {};

比如用戶自己定義了一個Annotation:

@Target({ ElementType.TYPE })

@Retention(RetentionPolicy.RUNTIME)

public @interface MyAnnotation {

}

然后用下面的寫法來創(chuàng)建abc這個bean虏肾,意思是當用戶顯式使用了@MyAnnotation(比如放在main class上),才會創(chuàng)建這個bean欢搜。

@Configuration

public class MyAutoConfiguration {

@Bean

// if comment this line, it will be fine.

@ConditionalOnBean(annotation = { MyAnnotation.class })

public String abc() {

return "abc";

}

}

這個功能很好封豪,但是在spring boot 1.4.5 版本之前都有問題,會導(dǎo)致FactoryBean提前初始化炒瘟。

在例子里吹埠,通過xml創(chuàng)建了javaVersion這個bean,想獲取到Java的版本號疮装。這里使用的是spring提供的一個調(diào)用static函數(shù)創(chuàng)建bean的技巧缘琅。

我們在代碼里獲取到這個javaVersion,然后打印出來:

@SpringBootApplication

@ImportResource("classpath:/demo.xml")

public class DemoApplication {

public static void main(String[] args) {

ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);

System.err.println(context.getBean("javaVersion"));

}

}

在實際運行時廓推,發(fā)現(xiàn)javaVersion的值是null刷袍。

這個其實是spring boot的鍋,要搞清楚這個問題樊展,先要看@ConditionalOnBean的實現(xiàn)呻纹。

@ConditionalOnBean實際上是在ConfigurationClassPostProcessor里被處理的,它實現(xiàn)了BeanDefinitionRegistryPostProcessor

BeanDefinitionRegistryPostProcessor是在spring早期被處理的

@ConditionalOnBean的具體處理代碼在org.springframework.boot.autoconfigure.condition.OnBeanCondition里

OnBeanCondition在獲取bean的Annotation時专缠,調(diào)用了beanFactory.getBeanNamesForAnnotation

private String[] getBeanNamesForAnnotation(

ConfigurableListableBeanFactory beanFactory, String type,

ClassLoader classLoader, boolean considerHierarchy) throws LinkageError {

String[] result = NO_BEANS;

try {

@SuppressWarnings("unchecked")

Class typeClass = (Class) ClassUtils

.forName(type, classLoader);

result = beanFactory.getBeanNamesForAnnotation(typeClass);

beanFactory.getBeanNamesForAnnotation 會導(dǎo)致FactoryBean提前初始化雷酪,創(chuàng)建出javaVersion里,傳入的${java.version.key}沒有被處理涝婉,值為null哥力。

spring boot 1.4.5 修復(fù)了這個問題:https://github.com/spring-projects/spring-boot/issues/8269。

實現(xiàn)spring boot starter要注意不能導(dǎo)致bean提前初始化

用戶在實現(xiàn)spring boot starter時墩弯,通常會實現(xiàn)Spring的一些接口吩跋,比如BeanFactoryPostProcessor接口,在處理時渔工,要注意不能調(diào)用類似beanFactory.getBeansOfType锌钮,beanFactory.getBeanNamesForAnnotation 這些函數(shù),因為會導(dǎo)致一些bean提前初始化涨缚。

而上面有提到PropertySourcesPlaceholderConfigurer的order是最低優(yōu)先級的轧粟,所以用戶自己實現(xiàn)的BeanFactoryPostProcessor接口在被回調(diào)時很有可能占位符還沒有被處理策治。

對于用戶自己定義的@ConfigurationProperties對象的注入,可以用類似下面的代碼:

@ConfigurationProperties(prefix = "spring.my")

public class MyProperties {

String key;

}

public static MyProperties buildMyProperties(ConfigurableEnvironment environment) {

MyProperties myProperties = new MyProperties();

if (environment != null) {

MutablePropertySources propertySources = environment.getPropertySources();

new RelaxedDataBinder(myProperties, "spring.my").bind(new PropertySourcesPropertyValues(propertySources));

}

return myProperties;

}

總結(jié)

占位符(${}表達式)是在PropertySourcesPlaceholderConfigurer里處理的兰吟,也就是BeanFactoryPostProcessor接口通惫;

spring的生命周期是比較復(fù)雜的事情,在實現(xiàn)了一些早期的接口時要小心混蔼,不能導(dǎo)致spring bean提前初始化履腋;

在早期的接口實現(xiàn)里,如果想要處理占位符惭嚣,可以利用spring自身的api遵湖,比如 environment.resolvePlaceholders(“${db.user}”)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末晚吞,一起剝皮案震驚了整個濱河市延旧,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌槽地,老刑警劉巖迁沫,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異捌蚊,居然都是意外死亡集畅,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進店門缅糟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來挺智,“玉大人,你說我怎么就攤上這事窗宦∩馄模” “怎么了?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵迫摔,是天一觀的道長沐扳。 經(jīng)常有香客問我,道長句占,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任躯嫉,我火速辦了婚禮纱烘,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘祈餐。我一直安慰自己擂啥,他們只是感情好,可當我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布帆阳。 她就那樣靜靜地躺著哺壶,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上山宾,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天至扰,我揣著相機與錄音,去河邊找鬼资锰。 笑死敢课,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的绷杜。 我是一名探鬼主播直秆,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼鞭盟!你這毒婦竟也來了圾结?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤齿诉,失蹤者是張志新(化名)和其女友劉穎疫稿,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鹃两,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡遗座,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了俊扳。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片途蒋。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖馋记,靈堂內(nèi)的尸體忽然破棺而出号坡,到底是詐尸還是另有隱情,我是刑警寧澤梯醒,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布宽堆,位于F島的核電站,受9級特大地震影響茸习,放射性物質(zhì)發(fā)生泄漏畜隶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一号胚、第九天 我趴在偏房一處隱蔽的房頂上張望籽慢。 院中可真熱鬧,春花似錦猫胁、人聲如沸箱亿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽届惋。三九已至髓帽,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間脑豹,已是汗流浹背郑藏。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留晨缴,地道東北人译秦。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像击碗,于是被迫代替她去往敵國和親筑悴。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容