简体   繁体   中英

Loading environment properties using Spring profiles

I am working in Spring, Java, Ant web application. I am using Spring profiling to load properties based on the enironment. Below is the sample

@Profile("dev")
@Component
@PropertySource("classpath:dev.properties")
public class DevPropertiesConfig{

}
@Profile("qa")
@Component
@PropertySource("classpath:qa.properties")
public class TestPropertiesConfig {

}

@Profile("live")
@Component
@PropertySource("classpath:live.properties")
public class LivePropertiesConfig{

}

In web.xml , we can give the profile

    <context-param>
        <param-name>spring.profiles.active</param-name>
        <param-value>dev</param-value>
    </context-param>

Now, my query is for every environment i need to create a separate Java class.

Question: Is it possible to have only one class like providing profile name as some binding parameter like @Profile({profile}) .

Also, let me know if there is other better option available to achieve the same.

There can be multiple profiles active at one time, so there is no single property to obtain the active profile. A general solution is to create an ApplicationContextInitializer which based on the active profiles loads additional configuration files.

public class ProfileConfigurationInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    public void initialize(final ConfigurableApplicationContext ctx) {
        ConfigurableEnvironment env = ctg.getEnvironment();
        String[] profiles = env.getActiveProfiles();
        if (!ArrayUtils.isEmpty(profiles)) {
            MutablePropertySources mps = env.getPropertySources();
            for (String profile : profiles) {
               Resource resource = new ClassPathResource(profile+".properties");
               if (resource.exists() ) {
                   mps.addLast(profile + "-properties", new ResourcePropertySource(resource);
               }
            }
        }
    }
}

Something like that should do the trick (might contain errors as I typed it from the top of my head).

Now in your web.xml include a context parameter named contextInitializerClasses and give it the name of your initializer.

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>your.package.ProfileConfigurationInitializer</param-value>
</context-param>

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