java - 使用 Spring 3.1 的属性抽象动态访问属性

标签 java spring

我正在尝试从 Spring 的 Environment property abstraction 动态访问属性.

我这样声明我的属性文件:

<context:property-placeholder
    location="classpath:server.common.properties,
    classpath:server.${my-environment}.properties" />

在我的属性文件 server.test.properties 中,我定义了以下内容:

myKey=foo

然后,给定以下代码:

@Component
public class PropertyTest {
    @Value("${myKey}")
    private String propertyValue;

    @Autowired 
    private PropertyResolver propertyResolver;

    public function test() {
         String fromResolver = propertyResolver.getProperty("myKey");
    }
}

当我运行这段代码时,我以 propertyValue='foo' 结束,但是 fromResolver=null;

接收 propertyValue 表示正在读取属性(我从代码的其他部分知道这一点)。但是,尝试动态查找它们是失败的。

为什么?如何在不使用 @Value 的情况下动态查找属性值?

最佳答案

只需添加一个 <context:property-placeholder/>不会向环境添加新的 PropertySource。如果您完整阅读了链接的文章,您会看到它建议注册 ApplicationContextInitializer为了添加新的 PropertySources,以便它们以您尝试使用它们的方式可用。

关于java - 使用 Spring 3.1 的属性抽象动态访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16705042/

相关文章:

java - Setter 方法有异常

java - 使用 Mockito,我如何验证一个方法是用某个参数调用的?

java - Java 中的数组返回内存分配而不是值

java - 合并列表中的多个 JObject - Json4s

spring - 使用 SpringJUnit4ClassRunner 时跳过运行时测试

spring - 不满意的依赖异常 : Error creating bean with name 'securityConfig'

java - 如何使用httpclient 4.3.6调用DCTM 7.1 REST API?

java - Spring数据事务控制

spring - grails 2.3.5 + redis-gorm 插件 + spring security 核心插件

java - 如何在Spring Data中进行Mongo聚合查询?