简体   繁体   中英

Access environment property using pure spring java configuration

I am writing a web application using Spring with a pure Java configuration (no xml). I'd like a solution to expose various environment specific properties depending on where my application is running (dev/test/prod). Using Spring xml config and the PropertyPlaceholderConfigurer via xml, I would have done something like this:

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:shift.properties</value>
            <value>classpath:shift-${env}.properties</value>
        </list>
    </property>
</bean>

In the Java configuration, the base of what I'm trying to do is the following:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.values.shift" })
public class WebConfig extends WebMvcConfigurerAdapter {

@Autowired
private static Environment springEnv;

@Bean
public static PropertyPlaceholderConfigurer propertyConfigurer() throws IOException {
    PropertyPlaceholderConfigurer props = new PropertyPlaceholderConfigurer();
    System.out.println("Environment:" + env.toString());
    props.setLocations(
            new Resource[] {
                    new ClassPathResource("shift.properties"), 
                    new ClassPathResource("shift-" + springEnv.getProperty("env") + ".properties")}
            );
    props.setIgnoreResourceNotFound(true);
    return props;
}

I have -Denv=localhost set as a VM argument on Tomcat. I also have it set as a system property on my mac (ie echo $env in the terminal outputs localhost)

I can't seem to figure out how to access that environment variable using pure Java. I have tried the following:

  • Use Spring Environment as shown in the code above.
  • @Value("#{ systemEnvironment['env'] }") for a new variable and access it as a string
  • @Value("#{ systemProperties['env'] }") for a new variable and access it as a string
  • @Value("${env}") for a new variable and access it as a string

All of the above return null. It would be great to see a working example of how to access environment variables using pure Java configuration in Spring.

Thanks for the help.

It tries to find 'env' property in properties file now.

You have missed to use systemPropertiesModeName method on PropertyPlaceholderConfigurer which will make your @Value("#{ systemProperties['env'] }") valid.

//edit:

dont use @Autowired on static fields.

//edit 2:

This is what im using:

@Configuration
public class PropertiesConfig {

@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return PropertyLoadHelper.getPropertySourcesPlaceholderConfigurer();
}

public static class PropertyLoadHelper {
    public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
        properties.setLocations(new ClassPathResource[]{
                new ClassPathResource("config/app." + System.getenv("ENV") + "properties"),
                new ClassPathResource("config/local.app." + System.getenv("ENV") + "properties"),
                new ClassPathResource("config/application.properties")
        });
        properties.setBeanName("app");
        properties.setLocalOverride(true);
        properties.setIgnoreResourceNotFound(true);
        return properties;
    }


    public static Properties loadProperties(String propertiesPath) {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource(propertiesPath));
        Properties properties = null;
        try {
            propertiesFactoryBean.afterPropertiesSet();
            properties = propertiesFactoryBean.getObject();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

}

}

differences: PropertySourcesPlaceholderConfigurer used, System.getenv used instead Autowired Environment. Maybe Environment cant be used before setting PropertyPlaceHolder bean?

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