我一直在尝试获取在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");
}
}
现在我创建了一个简单的单元测试,以查看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。
非常感谢任何帮助。谢谢!