【问题标题】:Spring @Bean factory method invoked ahead of @Value variable being resolved在解析 @Value 变量之前调用 Spring @Bean 工厂方法
【发布时间】: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


    【解决方案1】:

    如下更改您的配置,以便首先初始化 myProps bean

    @配置 @ImportResource({"classpath:configurable-context.xml"})

    public class SecurityConfig {
    
        @Value("#{myProps['my.custom.key']}")
        private String someValue = null;
    
        @Bean
        @DependOn("myProps")
        public SomeObject someObject() {
            return new SomeObject(someValue);  
        }
    }
    

    或者使您的配置干净地使用环境抽象,如下所示

    @Configuration
    @PropertySource("classpath:application.properties")
        public class SecurityConfig {
    
                @Autowired
                private private Environment env;
    
                @Bean
                public SomeObject someObject() {
                    return new SomeObject(env.getProperty("my.custom.key"));  
                }
            }
    

    然后将 application.properties 文件添加到您的类路径的根目录,其中包含 my.custom.key=myVal 条目 这将不再需要一个 xml 应用程序上下文来定义一个硬编码的属性

    【讨论】:

    • 谢谢!如果可能,我想避免使用属性文件——至少现在我们有充分的理由保留 XML。我无法让您的 @DependsOn 解决方案发挥作用,但它启发了上面发布的解决方案。
    猜你喜欢
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多