Thursday, March 2, 2017

Spring profiles

Requirement

Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments.

I'm working on 2 applications:

  1. with Spring Boot (1.3)
  2. legacy Spring XML (Spring version 3.2.)
Requirements are to have active profiles define in properties file. This is easy and by default for Spring Boot application.

Setting active profiles in Spring Boot application


Define spring.profiles.active=myProfile inside properties file


Displaying active profile when application is starting:

@Autowired
protected Environment env;

@PostConstruct
void after() {
String[] activeProfiles = env.getActiveProfiles();
logger.info("\n** activeProfiles: " + Arrays.toString(activeProfiles));
}


Setting active profiles in legacy Spring applications (Spring 3.2)


Defining profile for legacy Spring application was done in web.xml:

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

<param-value>myProfile</param-value>
</context-param>


Read active profile inside JSP page:
String activeProfile = (String) pageContext.getServletContext().getInitParameter("spring.profiles.active");

To move this definition inside properties file, you need to implement org.springframework.context.ApplicationContextInitializer interface:

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment env = applicationContext.getEnvironment();
try {
env.getPropertySources().addFirst(new ResourcePropertySource("classpath:application.properties"));

String profile = env.getProperty("spring.profiles.active");
logger.info("env.getProperty('spring.profiles.active'): " + profile);

String[] activeProfiles = env.getActiveProfiles();
logger.info("env.getActiveProfiles: " + Arrays.toString(activeProfiles));

// logger.info("changing active profile to ...");
// env.setActiveProfiles("newProfile");
} catch (IOException e) {
logger.info("file not found...");
}
}


In web.xml register it as context-param:

<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>hr.samara.demo.config.SamaraInitializer</param-value>
</context-param>


After this change reading active profile in JSP page needs to change:

<%@page import="org.springframework.web.context.support.XmlWebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>

<%
ServletContext sc = pageContext.getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
String[] profiles = applicationContext.getEnvironment().getActiveProfiles();
%>

Ref:

http://www.baeldung.com/spring-profiles
https://www.mkyong.com/spring/spring-profiles-example/
spring-doc-Bean definition profiles
stackoverflow - How to set active spring 3.1 environment profile via a properites file and not via an env variable or system property

No comments:

Post a Comment