[英]Spring Value Injection Into Bean
我对春季非常陌生,我正在尝试了解价值注入。 我有以下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;
}
}
我不确定这种新方法的正确性。
application.properties将PropertySourcesPlaceholderConfigurer
bean添加到您的配置中。
@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();
}
}
一些说明:
static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer()
是@PropertySource起作用所必需的,以便注入@Value。
为了实现为部分.properties设置间接级别的目标,您有不同的解决方案:-如您所愿,您可以在@Value注入的变量中指定最终.properties文件的名称,但是您必须将此新的属性源添加到当前上下文中,然后刷新它(如果希望添加的值在其他@Value中可用),则需要访问Spring上下文API的某些“低级” API并进行仔细的bean依赖关系分析,
更简单的解决方案是使用一个环境变量(在运行时使用-D传递给JVM的变量,例如-DrunningEnv = dev | test | prod | whatever ...),然后使用该环境变量作为指向的路径组件到您目标的实际配置。 例:
classpath:configuration / $ {runningEnv} /cassandra.properties
您可以在@PropertySource中使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.