【问题标题】:Spring Value Injection Into Bean将 Spring 值注入到 Bean
【发布时间】:2015-11-13 15:55:50
【问题描述】:

我对 spring 很陌生,我正在尝试处理价值注入。我有以下 Spring Boot Bean:

@Configuration
public class GraphProductionConfig {

    @Value("${database.config}")
    private static String CONFIG;

    @Bean
    public static GraphFactory getGraphFactory(){
         return new GraphProductionFactory();
    }

    public static class GraphProductionFactory implements GraphFactory{
        public Graph buildGraph() {
            TitanGraph titanGraph = TitanFactory.open(CONFIG);
            Graph graph = titanGraph;
            graph.tx().onClose(Transaction.CLOSE_BEHAVIOR.ROLLBACK);
            return graph;
        }
    }
}

在我的 application.properties 文件中包含以下内容:

database.config="conf/titan-cassandra.properties";

我正在尝试将database.config 注入GraphProductionFactory,以便我可以使用不同的配置。我知道注入静态字段非常糟糕。我读过构造函数注入可能是可能的,但我希望我的GraphProductionFactory 保持静态。有关如何进行的任何建议?

编辑:

我已经能够使用以下方法实现所需的行为:

public static class GraphProductionFactory implements GraphFactory{
    @Value("${database.config}")
    private String CONFIG;

    public Graph buildGraph() {
        TitanGraph titanGraph = TitanFactory.open(CONFIG);
        Graph graph = titanGraph;
        graph.tx().onClose(Transaction.CLOSE_BEHAVIOR.ROLLBACK);
        return graph;
    }
}

我不确定这种新方法有多正确。

【问题讨论】:

  • 你不能在@Configuration类中使用构造函数注入,但是你可以在bean方法上使用参数。

标签: java spring spring-mvc dependency-injection spring-boot


【解决方案1】:

application.properties将PropertySourcesPlaceholderConfigurer bean a 添加到您的配置中。

@Configuration   
@PropertySource("classpath:application.properties")//location of your property file
public class GraphProductionConfig {

             @Value("${database.config}")
             private static String CONFIG;

            //other bean configuration
            //..
            @Bean
            static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
                return new PropertySourcesPlaceholderConfigurer();
            }

}

【讨论】:

  • 这将如何注入我需要的价值? database.config="conf/titan-cassandra.properties"; 在 application.properties 中。我可以使用PropertySourcesPlaceholderConfigurer 来获取价值吗?
  • @Fido 我想,那是你的应用程序属性,PropertySource ("the location of your property file")
  • 我应该更清楚我所追求的值在我的 application.properties 中,该值恰好是指向另一个配置文件的字符串。
【解决方案2】:

一些说明:

static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer()

需要@PropertySource 才能工作,以便注入@Value。

为了实现为部分 .properties 设置间接级别的目标,您有不同的解决方案: - 如您所愿,您在@Value 注入的变量中指定最终 .properties 文件的名称,但是您必须将此新属性源添加到当前上下文,然后如果您希望添加的值可用,则刷新它在其他 @Value 中,这需要访问 Spring 上下文 API 的一些“低级”API 并仔细分析 bean 依赖关系,

  • 更简单的解决方案是使用一个环境变量(在运行时使用 -D 传递给 JVM 的变量,例如 -DrunningEnv=dev|test|prod|whatever...),然后使用该环境变量作为路径组件指向您的目标实际配置。 示例:

    类路径:配置/${runningEnv}/cassandra.properties

您可以在@PropertySource 中使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-19
    • 2011-05-29
    • 1970-01-01
    • 2023-04-09
    • 2011-09-09
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多