我一直试图获得一个在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;
}
}它通过一个ApplicationContext添加到ApplicationContextInitializer中:
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 -注释失败。就我在文档中所读到的内容而言,我配置中的PropertySourcesPlaceholderConfigurer应该会自动从环境中获取我的PropertySource,但显然它没有。我遗漏了什么吗?
我知道通过环境显式地访问属性是可取的,但是现有的应用程序经常使用@Value-注释。
任何帮助都是非常感谢的。谢谢!
发布于 2017-05-11 17:04:06
要使用@Value从属性源获取值,必须使用${}语法:
@Autowired
public void setFoo(@Value("${test}")String value){
foo=value;
}看看官方的文档。
https://stackoverflow.com/questions/43919380
复制相似问题