我一直在尝试获取在Spring Application中运行的自定义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");
}
}
现在,我创建了一个简单的单元测试,以查看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;
}
}
}
通过环境访问该值可以得到正确的结果(“ foobar”),但是使用@ Value-Annotation失败。据我在文档中阅读的内容,Configuration中的PropertySourcesPlaceholderConfigurer应该会自动从环境中提取PropertySource,但显然不会。我有什么想念的吗?
我知道最好通过环境显式访问属性,但是现有应用程序经常使用@ Value-Annotations。
任何帮助是极大的赞赏。谢谢!
要从属性源获取值,@Value
必须使用${}
语法:
@Autowired
public void setFoo(@Value("${test}")String value){
foo=value;
}
看一下官方文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句