Spring Boot Environment Properties reading based on activeprofile

By | 2018-11-11T10:25:48+00:00 September 9th, 2018|Spring Boot|0 Comments

In this tutorial, I am going to show how to read Spring Boot Environment Properties based on active-profile under Spring Boot Environment.

Spring Boot Environment Properties:

Properties play an important role almost all applications, and it may originate from a variety of sources like properties file, System Environment variables, JNDI, Java System Properties and etc.

Usually, each environment has its own property values, typically we refer these values in .properties or .yaml file. This tutorial helps you to read .properties file based on the environment in which the application is running.

Technologies:

  • Spring Boot 2.0.4.RELEASE
  • Java 8
  • Maven
  • IntelliJ

Application Structure:

Spring Boot Environment Properties

Pom.xml

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>com.onlinetutorialspoint</groupId>
  <artifactId>SpringBoot-Profiles-Example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>SpringBoot-Profiles-Example</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
  </properties>

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

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

  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

Create different application-{env}.property files for each environment.

application-Dev.properies
spring.profiles:Dev

app.logspath=/tmp/dev/app-name/logs/
app.username=devduser
app.password=devpassword
application-QA.properties
spring.profiles:QA

app.logspath=/tmp/qa/app-name/logs/
app.username=qauser
app.password=qapassword
application-Prod.properties
spring.profiles:Prod

app.logspath=/tmp/prod/app-name/logs/
app.username=produser
app.password=prodpassword

Spring Boot Main class.

Application.java
package com.onlinetutorialspoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

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

public class Application implements CommandLineRunner {
  @Autowired
  Environment env;

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    System.out.println("Logs Path -> "+env.getProperty("app.logspath"));
    System.out.println("User Name -> "+env.getProperty("app.username"));
    System.out.println("Password -> "+env.getProperty("app.password"));
  }
}

spring.profiles.active allows you to set active profile name among all defined profiles.

Here the Environment is an interface, it represents the environment in which the current application is running. The Environment object provides you to configure the property sources and resolving the properties from them.

Run the application with different profiles:

Terminal : mvn spring-boot:run -Dspring-boot.run.profiles=Dev
mvn spring-boot:run -Dspring-boot.run.profiles=Dev
[INFO] --- spring-boot-maven-plugin:2.0.4.RELEASE:run (default-cli) @ SpringBoot-Profiles-Example ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.4.RELEASE)
0.8.RELEASE.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
2018-09-09 16:15:32.607  INFO 12856 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.Annot
ationConfigServletWebServerApplicationContext@29ac8479: startup date [Sun Sep 09 16:15:28 IST 2018]; root of context hierarchy
2018-09-09 16:15:33.107  INFO 12856 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-09-09 16:15:33.247  INFO 12856 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-09-09 16:15:33.263  INFO 12856 --- [           main] com.onlinetutorialspoint.Application     : Started Application in 6.389 seconds (JVM running for 13.187)
.......
.......
Logs Path -> /tmp/dev/app-name/logs/
User Name -> devduser
Password -> devpassword

QA Environment:

mvn spring-boot:run -Dspring-boot.run.profiles=QA
Logs Path -> /tmp/qa/app-name/logs/
User Name -> qauser
Password -> qapassword

Prod Environment:

mvn spring-boot:run -Dspring-boot.run.profiles=Prod
Logs Path -> /tmp/prod/app-name/logs/
User Name -> produser
Password -> prodpassword

Happy Learning 🙂

Download Example

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment