[英]@ConfigurationProperties does not use PropertySourcesPlaceholderConfigurer
[英]Spring PropertySourcesPlaceholderConfigurer does not use custom PropertySource for @Value
我一直在嘗試獲得在Spring應用程序中運行的自定義PropertySource的一個非常基本的示例。
這是我的PropertySource:
public class RemotePropertySource extends PropertySource{
public RemotePropertySource(String name, Object source) {
super(name, source);
}
public RemotePropertySource(String name) {
super(name);
}
public Object getProperty(String s) {
return "foo"+s;
}
}
它通過ApplicationContextInitializer添加到ApplicationContext:
public class RemotePropertyApplicationContextInitializer implements ApplicationContextInitializer<GenericApplicationContext> {
public void initialize(GenericApplicationContext ctx) {
RemotePropertySource remotePropertySource = new RemotePropertySource("remote");
ctx.getEnvironment().getPropertySources().addFirst(remotePropertySource);
System.out.println("Initializer registered PropertySource");
}
}
現在我創建了一個簡單的Unit-Test來查看PropertySource是否正確使用:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RemotePropertySourceTest.ContextConfig.class, initializers = RemotePropertyApplicationContextInitializer.class)
public class RemotePropertySourceTest {
@Autowired
private UnderTest underTest;
@Autowired
Environment env;
@Test
public void testContext() {
assertEquals(env.getProperty("bar"),"foobar");
assertEquals(underTest.getFoo(),"footest");
}
@Component
protected static class UnderTest {
private String foo;
@Autowired
public void setFoo(@Value("test")String value){
foo=value;
}
public String getFoo(){
return foo;
}
}
@Configuration
@ComponentScan(basePackages = {"test.property"})
protected static class ContextConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
return configurer;
}
}
}
通過Environment訪問該值可以得到正確的結果(“foobar”),但使用@ Value-Annotation失敗。 據我在文檔中讀到,我的配置中的PropertySourcesPlaceholderConfigurer應該自動從環境中獲取我的PropertySource,但顯然它沒有。 有什么我想念的嗎?
我知道通過環境顯式訪問屬性是可取的,但現有的應用程序使用@ Value-Annotations很多。
任何幫助是極大的贊賞。 謝謝!
要使用@Value
從屬性源獲取值,您必須使用${}
語法:
@Autowired
public void setFoo(@Value("${test}")String value){
foo=value;
}
看看官方文檔 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.