Friday 13 September 2019

Spring boot: Programmatically find the active profile


Environment class provides ‘getActiveProfiles()’ method, it return currently active profiles.

Example
@Autowired
private Environment environment;

String[] activeProfiles = environment.getActiveProfiles();

Find the below working application.

HelloWorldController.java

package com.sample.app.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

 @Autowired
 private Environment environment;

 @RequestMapping("/")
 public String home() {
  return "Welcome to Spring boot Application development";
 }

 @RequestMapping("/profile")
 public String profile() {
  String[] activeProfiles = environment.getActiveProfiles();

  StringBuilder stringBuilder = new StringBuilder();

  for (String activeProfile : activeProfiles) {
   stringBuilder.append(activeProfile);
   stringBuilder.append("<br />");
  }
  return stringBuilder.toString();
 }
}


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.StandardEnvironment;

@SpringBootApplication
public class App {

 public static void main(String[] args) {
  SpringApplication application = new SpringApplication(App.class);

  ConfigurableEnvironment environment = new StandardEnvironment();
  environment.setActiveProfiles("dev", "prod");

  application.setEnvironment(environment);

  application.run(args);
 }

}


pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>springbootMisc</groupId>
 <artifactId>springbootMisc</artifactId>
 <version>1</version>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.6.RELEASE</version>
 </parent>

 <packaging>jar</packaging>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
 </dependencies>

</project>


Total project structure looks like below.

Run App.java.

Open the url ‘http://localhost:8080/profile’ in browser, you can see profiles information the browser.


You can download complete working application from this link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment