Setting an active profile for AbstractAnnotationConfigDispatcherServletInitializer that can be use with @PropertySource?

Viewed 6535

I'm using the AbstractAnnotationConfigDispatcherServletInitializer to configure my web application. I also have an @Configuration class I use for creating a few beans. In this class, I use the @PropertySource annotation to load a properties file for various settings (e.g. database connection details).

Currently, I use Maven profiles with Ant tasks to create the correct properties file(s) for my runtime environment. That is, I get Maven to move a "prod.properties" or "dev.properties" to "application.properties" (which the class uses) at build time. What I would like to do is use Spring profiles to eliminate this. I would like to be able to do the following:

@PropertySource( value = "classpath:/application-${spring.profiles.active}.properties")

I also want to set the profile without using any XML. So I would need to set the profile based on the presence of a system property. For example,

String currentEnvironment = systemProperties.getProperty("current.environment");
if (currentEnvironment == null) {
  ((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("production");
} else {
  ((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles(currentEnvironment);
}

I am not sure where I could do this, though. According to an answer to a related question, this could be done in an override of the createRootApplicationContext method in my initializer class. But, that answer also relies on the configuration classes being loaded before setting the profile.

Is what I want to do possible? If so, how?

2 Answers
Related