【发布时间】:2016-06-26 15:13:06
【问题描述】:
我遇到了 Spring Java/XML 配置的订单解析问题。似乎 @Value 注释没有在 @Bean 工厂方法被调用之前被解析,特别是在从外部 XML 配置加载属性时。
这是我正在做的事情的浓缩版:
@Configuration
@ImportResource({"classpath:configurable-context.xml"})
public class SecurityConfig {
@Value("#{myProps['my.custom.key']}")
private String someValue = null;
@Bean
public SomeObject someObject() {
return new SomeObject(someValue); // Fails because someValue == null
}
}
这是可配置的context.xml:
...
<util:map id="myProps">
<entry key="my.custom.key" value="myVal"/>
</util:map>
...
问题是someObject(...) 工厂方法在@Value 注释被评估为someValue 之前被调用,所以当时是null。
关于如何在调用工厂方法之前强制解析 someValue 变量有什么想法吗?
更新 受@Ekem 回复的启发,这段代码使用 XML 来源的属性为我工作:
@Configuration
@ImportResource({"classpath:configurable-context.xml"})
public class SecurityConfig {
@Resource(name = "myProps")
private Properties myProps;
@Bean
public SomeObject someObject() {
return new SomeObject(myProps.getProperty("my.custom.key")); // Now works :-)
}
}
【问题讨论】:
标签: spring configuration javabeans