javascript
Spring @Bean和PropertyPlaceHolderConfigurer
最近,我被我認為將是一個相當簡單的實現所困擾-考慮以下基于Spring Java的bean定義文件(
@Configuration ):
此處定義了一個bean“ sampleService”,該bean初始化為一個屬性,該屬性使用@Value注釋(使用屬性占位符字符串$ {test.prop})填充。
對此的測試如下:
@ContextConfiguration(classes=SampleConfig.class) @RunWith(SpringJUnit4ClassRunner.class) public class ConfigTest {@Autowiredprivate SampleService sampleService;@Testpublic void testConfig() {assertThat(sampleService.aMethod(), is("testproperty"));} }由于占位符$ {test.prop}根本無法解析,因此使用SampleConfig的當前實現會失敗。 為此的標準解決方法是注冊一個PropertySourcesPlaceholderConfigurer ,它是一個BeanFactoryPostProcessor,負責掃描所有已注冊的bean定義并注入已解析的占位符。 進行此更改后,@ Configuration文件如下所示:
@Configuration @PropertySource("classpath:root/test.props") public class SampleConfig { @Value("${test.prop}")private String attr;@Beanpublic SampleService sampleService() {return new SampleService(attr);}@Beanpublic PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {return new PropertySourcesPlaceholderConfigurer();} }但是,在添加了屬性解析器后,測試仍然失敗,這一次sampleService返回的值為null,甚至沒有占位符值!
導致該問題的原因是,在@Configuration內部使用諸如@ Autowired,@ Value和@PostConstruct之類的批注的情況下,任何BeanFactoryPostProcessor Bean都必須使用static修飾符進行聲明。 否則,包含的@Configuration類將在很早之前實例化,并且負責解析諸如@ Value,@ Autowired等注釋的BeanPostProcessors無法對其執行操作。
此修復程序在@Bean的javadoc中有詳細記錄,還記錄了一條消息,提供了解決方法:
WARN : org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method RootConfig.placeHolderConfigurer is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean Javadoc for complete details因此,使用此修復程序,新的工作配置如下:
@Configuration @PropertySource("classpath:root/test.props") public class SampleConfig { @Value("${test.prop}")private String attr;@Beanpublic SampleService sampleService() {return new SampleService(attr);}@Beanpublic static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {return new PropertySourcesPlaceholderConfigurer();} }參考文獻:
- 吉拉記錄本期
- @Bean Javadoc
- Stackoverflow中的相關問題
翻譯自: https://www.javacodegeeks.com/2013/07/spring-bean-and-propertyplaceholderconfigurer.html
總結
以上是生活随笔為你收集整理的Spring @Bean和PropertyPlaceHolderConfigurer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 咋看电脑上的所有驱动(如何查看电脑里的驱
- 下一篇: 使用AspectJ审计Spring MV