SpringBoot之那些注入不了的Spring占位符(${}表達(dá)式)問(wèn)題
Spring里的占位符
spring里的占位符通常表現(xiàn)的形式是:
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
</bean>或者
@Configuration
@ImportResource("classpath:/com/acme/properties-config.xml")
public class AppConfig {
@Value("${jdbc.url}")
private String url;
}Spring應(yīng)用在有時(shí)會(huì)出現(xiàn)占位符配置沒(méi)有注入,原因可能是多樣的。
本文介紹兩種比較復(fù)雜的情況。
占位符是在Spring生命周期的什么時(shí)候處理的
Spirng在生命周期里關(guān)于Bean的處理大概可以分為下面幾步:
- 加載Bean定義(從xml或者從
@Import等) - 處理
BeanFactoryPostProcessor - 實(shí)例化Bean
- 處理Bean的property注入
- 處理
BeanPostProcessor

當(dāng)然這只是比較理想的狀態(tài),實(shí)際上因?yàn)镾pring Context在構(gòu)造時(shí),也需要?jiǎng)?chuàng)建很多內(nèi)部的Bean,應(yīng)用在接口實(shí)現(xiàn)里也會(huì)做自己的各種邏輯,整個(gè)流程會(huì)非常復(fù)雜。
那么占位符(${}表達(dá)式)是在什么時(shí)候被處理的?
- 實(shí)際上是在org.springframework.context.support.PropertySourcesPlaceholderConfigurer里處理的,它會(huì)訪問(wèn)了每一個(gè)bean的BeanDefinition,然后做占位符的處理
- PropertySourcesPlaceholderConfigurer實(shí)現(xiàn)了BeanFactoryPostProcessor接口
- PropertySourcesPlaceholderConfigurer的 order是Ordered.LOWEST_PRECEDENCE,也就是最低優(yōu)先級(jí)的
結(jié)合上面的Spring的生命周期,如果Bean的創(chuàng)建和使用在PropertySourcesPlaceholderConfigurer之前,那么就有可能出現(xiàn)占位符沒(méi)有被處理的情況。
例子1
Mybatis 的 MapperScannerConfigurer引起的占位符沒(méi)有處理
首先應(yīng)用自己在代碼里創(chuàng)建了一個(gè)DataSource,其中${db.user}是希望從application.properties里注入的。
代碼在運(yùn)行時(shí)會(huì)打印出user的實(shí)際值。
@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)用用代碼的方式來(lái)初始化mybatis相關(guān)的配置,依賴上面創(chuàng)建的DataSource對(duì)象
@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;
}
}當(dāng)代碼運(yùn)行時(shí),輸出結(jié)果是:
user: ${db.user}
為什么會(huì)user這個(gè)變量沒(méi)有被注入?
分析下Bean定義,可以發(fā)現(xiàn)MapperScannerConfigurer它實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor。
這個(gè)接口在是Spring掃描Bean定義時(shí)會(huì)回調(diào)的,遠(yuǎn)早于BeanFactoryPostProcessor。
所以原因是:
MapperScannerConfigurer它實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor,所以它會(huì)Spring的早期會(huì)被創(chuàng)建- 從bean的依賴關(guān)系來(lái)看,mapperScannerConfigurer依賴了sqlSessionFactory1,sqlSessionFactory1
- 依賴了dataSource1
MyDataSourceConfig里的dataSource1被提前初始化,沒(méi)有經(jīng)過(guò)PropertySourcesPlaceholderConfigurer的處理,所以@Value("${db.user}") String user里的占位符沒(méi)有被處理
要解決這個(gè)問(wèn)題,可以在代碼里,顯式來(lái)處理占位符:
environment.resolvePlaceholders("${db.user}")例子2
Spring boot自身實(shí)現(xiàn)問(wèn)題,導(dǎo)致Bean被提前初始化
Spring Boot里提供了@ConditionalOnBean,這個(gè)方便用戶在不同條件下來(lái)創(chuàng)建bean。
里面提供了判斷是否存在bean上有某個(gè)注解的功能。
@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<? extends Annotation>[] annotation() default {};比如用戶自己定義了一個(gè)Annotation:
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}然后用下面的寫法來(lái)創(chuàng)建abc這個(gè)bean,意思是當(dāng)用戶顯式使用了@MyAnnotation(比如放在main class上),才會(huì)創(chuàng)建這個(gè)bean。
@Configuration
public class MyAutoConfiguration {
@Bean
// if comment this line, it will be fine.
@ConditionalOnBean(annotation = { MyAnnotation.class })
public String abc() {
return "abc";
}
}這個(gè)功能很好,但是在spring boot 1.4.5 版本之前都有問(wèn)題,會(huì)導(dǎo)致FactoryBean提前初始化。
在例子里,通過(guò)xml創(chuàng)建了javaVersion這個(gè)bean,想獲取到j(luò)ava的版本號(hào)。
這里使用的是spring提供的一個(gè)調(diào)用static函數(shù)創(chuàng)建bean的技巧。
<bean id="sysProps" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass" value="java.lang.System" />
<property name="targetMethod" value="getProperties" />
</bean>
<bean id="javaVersion" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="sysProps" />
<property name="targetMethod" value="getProperty" />
<property name="arguments" value="${java.version.key}" />
</bean>我們?cè)诖a里獲取到這個(gè)javaVersion,然后打印出來(lái):
@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"));
}
}在實(shí)際運(yùn)行時(shí),發(fā)現(xiàn)javaVersion的值是null。
這個(gè)其實(shí)是spring boot的鍋,要搞清楚這個(gè)問(wèn)題,先要看@ConditionalOnBean的實(shí)現(xiàn)。
@ConditionalOnBean實(shí)際上是在ConfigurationClassPostProcessor里被處理的,它實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessorBeanDefinitionRegistryPostProcessor是在spring早期被處理的- @
ConditionalOnBean的具體處理代碼在org.springframework.boot.autoconfigure.condition.OnBeanCondition里 OnBeanCondition在獲取bean的Annotation時(shí),調(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<? extends Annotation> typeClass = (Class<? extends Annotation>) ClassUtils
.forName(type, classLoader);
result = beanFactory.getBeanNamesForAnnotation(typeClass);beanFactory.getBeanNamesForAnnotation會(huì)導(dǎo)致FactoryBean提前初始化,創(chuàng)建出javaVersion里,傳入的${java.version.key}沒(méi)有被處理,值為null。- spring boot 1.4.5 修復(fù)了這個(gè)問(wèn)題:https://github.com/spring-projects/spring-boot/issues/8269
實(shí)現(xiàn)spring boot starter要注意不能導(dǎo)致bean提前初始化
用戶在實(shí)現(xiàn)spring boot starter時(shí),通常會(huì)實(shí)現(xiàn)Spring的一些接口,比如BeanFactoryPostProcessor接口,在處理時(shí),要注意不能調(diào)用類似beanFactory.getBeansOfType,beanFactory.getBeanNamesForAnnotation 這些函數(shù),因?yàn)闀?huì)導(dǎo)致一些bean提前初始化。
而上面有提到PropertySourcesPlaceholderConfigurer的order是最低優(yōu)先級(jí)的,所以用戶自己實(shí)現(xiàn)的BeanFactoryPostProcessor接口在被回調(diào)時(shí)很有可能占位符還沒(méi)有被處理。
對(duì)于用戶自己定義的@ConfigurationProperties對(duì)象的注入,可以用類似下面的代碼:
@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é)
- 占位符(${}表達(dá)式)是在
PropertySourcesPlaceholderConfigurer里處理的,也就是BeanFactoryPostProcessor接口 - spring的生命周期是比較復(fù)雜的事情,在實(shí)現(xiàn)了一些早期的接口時(shí)要小心,不能導(dǎo)致spring bean提前初始化
- 在早期的接口實(shí)現(xiàn)里,如果想要處理占位符,可以利用spring自身的api,比如
environment.resolvePlaceholders("${db.user}")
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解SpringBoot集成消息隊(duì)列的案例應(yīng)用
Message?Queue又名消息隊(duì)列,是一種異步通訊的中間件??梢岳斫鉃猷]局,發(fā)送者將消息投遞到郵局,然后郵局幫我們發(fā)送給具體的接收者,具體發(fā)送過(guò)程和時(shí)間與我們無(wú)關(guān)。?消息隊(duì)列是分布式系統(tǒng)中重要的組件,消息隊(duì)列主要解決了應(yīng)用耦合、異步處理、流量削鋒等問(wèn)題2022-04-04
java實(shí)現(xiàn)發(fā)送郵箱驗(yàn)證碼
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)發(fā)送郵箱驗(yàn)證碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
Java實(shí)現(xiàn)優(yōu)雅日期處理的方案詳解
在我們的日常工作中,需要經(jīng)常處理各種格式,各種類似的的日期或者時(shí)間,下面我們就來(lái)看看如何使用java處理這樣的日期問(wèn)題吧,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-04-04
java實(shí)現(xiàn)python session功能代碼實(shí)例
這篇文章主要介紹了java實(shí)現(xiàn)python session功能代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
MyBatis Plus復(fù)合主鍵問(wèn)題的解決
在數(shù)據(jù)庫(kù)設(shè)計(jì)中,有時(shí)候需要使用復(fù)合主鍵來(lái)唯一標(biāo)識(shí)表中的一行數(shù)據(jù),本文將為您詳細(xì)介紹MyBatis Plus中復(fù)合主鍵的問(wèn)題以及解決方案,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09
springboot-mysql-HikariCP集成過(guò)程
HiKariCP opens new window是數(shù)據(jù)庫(kù)連接池的一個(gè)后起之秀,號(hào)稱性能最好,可以完美地 PK 掉其他連接池,這篇文章主要介紹了springboot-mysql-HikariCP集成過(guò)程,需要的朋友可以參考下2023-07-07
SpringBoot Import及自定義裝配實(shí)現(xiàn)方法解析
這篇文章主要介紹了SpringBoot Import及自定義裝配實(shí)現(xiàn)方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08

