Last active
August 29, 2015 14:07
-
-
Save jeffsheets/429b5454f9008aeccb1c to your computer and use it in GitHub Desktop.
Spring Profile specific properties files, similar to Spring Boot (or Grails) properties. This registers application-*.properties for all Active (or Default) spring profiles.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Register this with the DispatcherServlet in a ServletInitializer class like: | |
* dispatcherServlet.setContextInitializers(new PropertiesInitializer()); | |
*/ | |
public class PropertiesInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { | |
private static final Logger log = LoggerFactory.getLogger(PropertiesInitializer.class); | |
/** | |
* Runs as appInitializer so properties are wired before spring beans | |
*/ | |
@Override | |
public void initialize(ConfigurableApplicationContext applicationContext) { | |
ConfigurableEnvironment env = applicationContext.getEnvironment(); | |
String[] activeProfiles = getActiveProfiles(env); | |
for (String profileName : activeProfiles) { | |
log.info("Loading properties for Spring Active Profile: {}", profileName); | |
try { | |
ResourcePropertySource propertySource = new ResourcePropertySource(profileName + "EnvProperties", "classpath:application-" + profileName + ".properties"); | |
env.getPropertySources().addLast(propertySource); | |
} catch (IOException e) { | |
log.error("ERROR during environment properties setup - TRYING TO LOAD: " + profileName, e); | |
//Okay to silently fail here, as we might have profiles that do not have properties files (like dev1, dev2, etc) | |
} | |
} | |
} | |
/** | |
* Returns either the ActiveProfiles, or if empty, then the DefaultProfiles from Spring | |
*/ | |
protected String[] getActiveProfiles(ConfigurableEnvironment env) { | |
String[] activeProfiles = env.getActiveProfiles(); | |
if (activeProfiles.length > 0) { | |
log.debug("Using registered Spring Active Profiles: {}", StringUtils.join(activeProfiles, ", ")); | |
return activeProfiles; | |
} | |
String[] defaultProfiles = env.getDefaultProfiles(); | |
log.debug("No Active Profiles found, using Spring Default Profiles: {}", StringUtils.join(defaultProfiles, ", ")); | |
return defaultProfiles; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment