SpringBoot之那些注入不了的Spring占位符(${}表達式)問題
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應用在有時會出現(xiàn)占位符配置沒有注入,原因可能是多樣的。
本文介紹兩種比較復雜的情況。
占位符是在Spring生命周期的什么時候處理的
Spirng在生命周期里關(guān)于Bean的處理大概可以分為下面幾步:
- 加載Bean定義(從xml或者從
@Import
等) - 處理
BeanFactoryPostProcessor
- 實例化Bean
- 處理Bean的property注入
- 處理
BeanPostProcessor
當然這只是比較理想的狀態(tài),實際上因為Spring Context在構(gòu)造時,也需要創(chuàng)建很多內(nèi)部的Bean,應用在接口實現(xiàn)里也會做自己的各種邏輯,整個流程會非常復雜。
那么占位符(${}表達式)是在什么時候被處理的?
- 實際上是在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引起的占位符沒有處理
首先應用自己在代碼里創(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; } }
然后應用用代碼的方式來初始化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)問題,導致Bean被提前初始化
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<? extends Annotation>[] 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 版本之前都有問題,會導致FactoryBean提前初始化。
在例子里,通過xml創(chuàng)建了javaVersion
這個bean,想獲取到j(luò)ava的版本號。
這里使用的是spring提供的一個調(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>
我們在代碼里獲取到這個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<? extends Annotation> typeClass = (Class<? extends Annotation>) ClassUtils .forName(type, classLoader); result = beanFactory.getBeanNamesForAnnotation(typeClass);
beanFactory.getBeanNamesForAnnotation
會導致FactoryBean
提前初始化,創(chuàng)建出javaVersion
里,傳入的${java.version.key}
沒有被處理,值為null。- spring boot 1.4.5 修復了這個問題:https://github.com/spring-projects/spring-boot/issues/8269
實現(xiàn)spring boot starter要注意不能導致bean提前初始化
用戶在實現(xiàn)spring boot starter時,通常會實現(xiàn)Spring的一些接口,比如BeanFactoryPostProcessor
接口,在處理時,要注意不能調(diào)用類似beanFactory.getBeansOfType
,beanFactory.getBeanNamesForAnnotation
這些函數(shù),因為會導致一些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的生命周期是比較復雜的事情,在實現(xiàn)了一些早期的接口時要小心,不能導致spring bean提前初始化
- 在早期的接口實現(xiàn)里,如果想要處理占位符,可以利用spring自身的api,比如
environment.resolvePlaceholders("${db.user}")
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot mybatisplus如何解決分頁組件IPage失效問題
這篇文章主要介紹了Springboot mybatisplus如何解決分頁組件IPage失效問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08Java數(shù)據(jù)結(jié)構(gòu)與算法之插值查找解析
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)與算法之插值查找解析,插值查找算法類似于二分查找,不同的就是插值查找每次從自適應mid處開始查找,需要的朋友可以參考下2023-12-12Springboot之日志、配置文件、接口數(shù)據(jù)如何脫敏
本文主要介紹了Springboot之配置文件數(shù)據(jù)脫敏、接口返回數(shù)據(jù)脫敏、日志文件數(shù)據(jù)脫敏三個方面,需要了解學習的小伙伴快跟隨小編的腳步一起去看看吧2021-09-09Spring Security 密碼驗證動態(tài)加鹽的驗證處理方法
小編最近在改造項目,需要將gateway整合security在一起進行認證和鑒權(quán),今天小編給大家分享Spring Security 密碼驗證動態(tài)加鹽的驗證處理方法,感興趣的朋友一起看看吧2021-06-06Java開發(fā)工具-scala處理json格式利器-json4s詳解
這篇文章主要介紹了開發(fā)工具-scala處理json格式利器-json4s,文章中處理方法講解的很清楚,有需要的同學可以研究下2021-02-02基于Spring Boot DevTools實現(xiàn)開發(fā)過程優(yōu)化
這篇文章主要介紹了基于Spring Boot DevTools實現(xiàn)開發(fā)過程優(yōu)化,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09