首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring PropertySourcesPlaceholderConfigurer不对@ PropertySource使用自定义PropertySource。

Spring PropertySourcesPlaceholderConfigurer不对@ PropertySource使用自定义PropertySource。
EN

Stack Overflow用户
提问于 2017-05-11 15:13:27
回答 1查看 715关注 0票数 4

我一直试图获得一个在Spring中运行的自定义PropertySource的非常基本的示例。

这是我的PropertySource:

代码语言:javascript
复制
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中:

代码语言:javascript
复制
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:

代码语言:javascript
复制
@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-注释。

任何帮助都是非常感谢的。谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-11 17:04:06

要使用@Value从属性源获取值,必须使用${}语法:

代码语言:javascript
复制
@Autowired
public void setFoo(@Value("${test}")String value){
    foo=value;
}

看看官方的文档

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43919380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档