您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。
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ù)雜的情況。
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)有被處理的情況。
首先應(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:h3:?/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
依賴了dataSource1MyDataSourceConfig
里的dataSource1
被提前初始化,沒(méi)有經(jīng)過(guò)PropertySourcesPlaceholderConfigurer
的處理,所以@Value("${db.user}") String user
里的占位符沒(méi)有被處理
要解決這個(gè)問(wèn)題,可以在代碼里,顯式來(lái)處理占位符:
environment.resolvePlaceholders("${db.user}")
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 { }
然后用下面的寫(xiě)法來(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)了BeanDefinitionRegistryPostProcessor
BeanDefinitionRegistryPostProcessor
是在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)題
用戶在實(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; }
讀到這里,這篇“SpringBoot之注入不了的Spring占位符問(wèn)題怎么解決”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。