spring java 配置环境变量
spring java configuration environment variables
我正在使用 Spring,我正在从 xml 配置切换到 java 配置。
实际上我遇到了环境变量的问题,因为我不明白我可以通过哪种方式检索环境变量的值。
使用 xml 配置我有以下内容
<bean id="myAppProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="file:${MY_ENV_VAR}/applicationConfiguration/external.properties"/>
<property name="fileEncoding" value="UTF-8"/>
</bean>
我不明白我可以用什么方式将以前的 xml 代码切换到相同的 java 配置。我试过这个
@Bean
public PropertiesFactoryBean cvlExternalProperties() {
PropertiesFactoryBean res = new PropertiesFactoryBean();
res.setFileEncoding("UTF-8");
res.setLocation(new FileSystemResource("file:${MY_ENV_VAR}/applicationConfiguration/external.properties"));
return res;
}
但是没有成功。
我已经尝试使用环境 class 但没有任何改进。
你能帮帮我吗?
您使用 @Value
注释或 @ConfigProperties
-类
注入它们
试试这个:
@Bean
public PropertiesFactoryBean cvlExternalProperties(@Value("${MY_ENV_VAR}") String envVar) {
PropertiesFactoryBean res = new PropertiesFactoryBean();
res.setFileEncoding("UTF-8");
res.setLocation(new FileSystemResource("file:" + envVar + "/applicationConfiguration/external.propert ies"));
return res;
}
您可以在这里找到更多内容:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config
我找到了解决方案,但我正在尝试最好的解决方案。
可行的解决方案是
- 在@Configuration中添加这个字段class
@Autowired
private Environment env;
- 使用该字段解析环境变量名称
env.resolvePlaceholders("${MY_ENV_VAR}")
但我正在寻找一种解决方案,允许我声明我想从哪个域检索变量。例如系统变量、环境变量或外部属性。
你能帮帮我吗?
我正在使用 Spring,我正在从 xml 配置切换到 java 配置。 实际上我遇到了环境变量的问题,因为我不明白我可以通过哪种方式检索环境变量的值。
使用 xml 配置我有以下内容
<bean id="myAppProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="file:${MY_ENV_VAR}/applicationConfiguration/external.properties"/>
<property name="fileEncoding" value="UTF-8"/>
</bean>
我不明白我可以用什么方式将以前的 xml 代码切换到相同的 java 配置。我试过这个
@Bean
public PropertiesFactoryBean cvlExternalProperties() {
PropertiesFactoryBean res = new PropertiesFactoryBean();
res.setFileEncoding("UTF-8");
res.setLocation(new FileSystemResource("file:${MY_ENV_VAR}/applicationConfiguration/external.properties"));
return res;
}
但是没有成功。 我已经尝试使用环境 class 但没有任何改进。
你能帮帮我吗?
您使用 @Value
注释或 @ConfigProperties
-类
试试这个:
@Bean
public PropertiesFactoryBean cvlExternalProperties(@Value("${MY_ENV_VAR}") String envVar) {
PropertiesFactoryBean res = new PropertiesFactoryBean();
res.setFileEncoding("UTF-8");
res.setLocation(new FileSystemResource("file:" + envVar + "/applicationConfiguration/external.propert ies"));
return res;
}
您可以在这里找到更多内容:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config
我找到了解决方案,但我正在尝试最好的解决方案。
可行的解决方案是
- 在@Configuration中添加这个字段class
@Autowired private Environment env;
- 使用该字段解析环境变量名称
env.resolvePlaceholders("${MY_ENV_VAR}")
但我正在寻找一种解决方案,允许我声明我想从哪个域检索变量。例如系统变量、环境变量或外部属性。
你能帮帮我吗?