java – Spring PropertySourcesPlaceholderConfigurer不为@Value使用自定义PropertySource
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Spring PropertySourcesPlaceholderConfigurer不为@Value使用自定义PropertySource,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2218字,纯文字阅读大概需要4分钟。
内容图文
![java – Spring PropertySourcesPlaceholderConfigurer不为@Value使用自定义PropertySource](/upload/InfoBanner/zyjiaocheng/789/5f275f625386464b8f833a175831cba5.jpg)
我一直在尝试获得在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;
}
看看官方documentation.
内容总结
以上是互联网集市为您收集整理的java – Spring PropertySourcesPlaceholderConfigurer不为@Value使用自定义PropertySource全部内容,希望文章能够帮你解决java – Spring PropertySourcesPlaceholderConfigurer不为@Value使用自定义PropertySource所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。