简体   繁体   English

Spring Java配置环境变量

[英]spring java configuration environment variables

I'm using Spring and I'm switching from the xml configuration to the java configuration. 我正在使用Spring,并且正在从xml配置切换到Java配置。 Actually I'm facing a problem with the environment variables because I'm not understanding in which way I can retrieve the value of a environment variable. 实际上,我面临环境变量的问题,因为我不了解如何以哪种方式检索环境变量的值。

With the xml configuration I Have the following 使用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>

I don't understand in which way I can switch the previous xml code to the same java configuration. 我不知道可以用哪种方式将先前的xml代码切换到相同的Java配置。 I've tried with this 我已经试过了

@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;
}

But no success. 但是没有成功。 I've tried with the Environment class but any improvement. 我已经尝试了环境类,但有任何改进。

Can you help me? 你能帮助我吗?

You inject them using the @Value annotation or @ConfigProperties -Classes 您可以使用@Value注释或@ConfigProperties -Classes注入它们

Try this one: 试试这个:

@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;
}

More stuff you find here: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config 您可以在此处找到更多内容: http : //docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config

I've found a solution but I'm trying a best one. 我找到了一种解决方案,但我正在尝试最好的解决方案。

The working solution is 工作解决方案是

  1. add this field in the @Configuration class 在@Configuration类中添加此字段
  @Autowired private Environment env; 
  1. use that field to resolve the environment variable name 使用该字段来解析环境变量名称

env.resolvePlaceholders("${MY_ENV_VAR}") env.resolvePlaceholders( “$ {} MY_ENV_VAR”)

But I'm looking for a solution that allows me to declare from which domain I want to retrieve the variable. 但是我正在寻找一种解决方案,该解决方案允许我声明要从哪个域检索变量。 For example system variables, environment variables or external properties. 例如系统变量,环境变量或外部属性。

Can you help me? 你能帮助我吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM