package com.mytutorial.configuration;
import static org.springframework.core.env.StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePropertySource;
public class MyAppApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
public static final String DEFAULT_APPLICATION_PROPERTIES = "myapp-service.properties";
private static final Logger LOG = LoggerFactory.getLogger(MyAppApplicationContextInitializer.class);
@Override
public void initialize(final ConfigurableApplicationContext applicationContext) {
final ConfigurableEnvironment environment = applicationContext.getEnvironment();
final MutablePropertySources propertySources = environment.getPropertySources();
propertySources.addAfter(SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, getApplicationProperties(environment));
}
/**
* Loads application properties from the configured resource location.
*/
protected PropertySource<?> getApplicationProperties(final ConfigurableEnvironment environment) {
try {
final Resource propertiesResource = new ClassPathResource(DEFAULT_APPLICATION_PROPERTIES);
final ResourcePropertySource propertySource = new ResourcePropertySource(propertiesResource);
LOG.info("Configured application properties from: {}", propertySource);
return propertySource;
} catch (final IOException ex) {
throw new RuntimeException("Unable to load application properties from default location: "
+ DEFAULT_APPLICATION_PROPERTIES, ex);
}
}
}