简体   繁体   中英

spring java configuration environment variables

I'm using Spring and I'm switching from the xml configuration to the java configuration. 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

<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. 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

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

I've found a solution but I'm trying a best one.

The working solution is

  1. add this field in the @Configuration class
  @Autowired private Environment env; 
  1. use that field to resolve the environment variable name

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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