
[英]@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.