【发布时间】: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