Spring Boot Environment Properties reading based on activeProfile

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show how to read Spring Boot Environment Properties based on active-profile under Spring Boot Environment.
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.
Spring Boot 2.0.4.RELEASE
Java 8
Maven
IntelliJ
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.
spring.profiles:Dev

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

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

app.logspath=/tmp/prod/app-name/logs/
app.username=produser
app.password=prodpassword
Spring Boot Main class.
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:
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:
Logs Path -> /tmp/qa/app-name/logs/
User Name -> qauser
Password -> qapassword

Prod Environment:
Logs Path -> /tmp/prod/app-name/logs/
User Name -> produser
Password -> prodpassword

Happy Learning 🙂


SpringBoot-Profiles-Example

File size: 86 KB
Downloads: 478


How to Configure Spring Profile in Tomcat ?
SSL Spring Boot HTTPs Enabling Example
How to use Spring Boot Random Port
Spring Boot RabbitMQ Consumer Messages Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
Spring Boot FileUpload Ajax Example
Spring Boot Basic Authentication Example
Properties class Example in Java
JDBC Connection with Properties file
How to Rotate an Array to Left direction based on user input ?
Spring Boot MongoDB + Spring Data Example
Simple Spring Boot Example
Spring Boot MVC Example Tutorials

How to Configure Spring Profile in Tomcat ?
SSL Spring Boot HTTPs Enabling Example
How to use Spring Boot Random Port
Spring Boot RabbitMQ Consumer Messages Example
How to change Spring Boot Tomcat Port Number
How To Change Spring Boot Context Path
Spring Boot Validation Login Form Example
Spring Boot FileUpload Ajax Example
Spring Boot Basic Authentication Example
Properties class Example in Java
JDBC Connection with Properties file
How to Rotate an Array to Left direction based on user input ?
Spring Boot MongoDB + Spring Data Example
Simple Spring Boot Example
Spring Boot MVC Example Tutorials
 


Δ
 Spring Boot – Hello World
 Spring Boot – MVC Example
 Spring Boot- Change Context Path
 Spring Boot – Change Tomcat Port Number
 Spring Boot – Change Tomcat to Jetty Server
 Spring Boot – Tomcat session timeout
 Spring Boot – Enable Random Port
 Spring Boot – Properties File
 Spring Boot – Beans Lazy Loading
 Spring Boot – Set Favicon image
 Spring Boot – Set Custom Banner
 Spring Boot – Set Application TimeZone
 Spring Boot – Send Mail
 Spring Boot – FileUpload Ajax
 Spring Boot – Actuator
 Spring Boot – Actuator Database Health Check
 Spring Boot – Swagger
 Spring Boot – Enable CORS
 Spring Boot – External Apache ActiveMQ Setup
 Spring Boot – Inmemory Apache ActiveMq
 Spring Boot – Scheduler Job
 Spring Boot – Exception Handling
 Spring Boot – Hibernate CRUD
 Spring Boot – JPA Integration CRUD
 Spring Boot – JPA DataRest CRUD
 Spring Boot – JdbcTemplate CRUD
 Spring Boot – Multiple Data Sources Config
 Spring Boot – JNDI Configuration
 Spring Boot – H2 Database CRUD
 Spring Boot – MongoDB CRUD
 Spring Boot – Redis Data CRUD
 Spring Boot – MVC Login Form Validation
 Spring Boot – Custom Error Pages
 Spring Boot – iText PDF
 Spring Boot – Enable SSL (HTTPs)
 Spring Boot – Basic Authentication
 Spring Boot – In Memory Basic Authentication
 Spring Boot – Security MySQL Database Integration
 Spring Boot – Redis Cache – Redis Server
 Spring Boot – Hazelcast Cache
 Spring Boot – EhCache
 Spring Boot – Kafka Producer
 Spring Boot – Kafka Consumer
 Spring Boot – Kafka JSON Message to Kafka Topic
 Spring Boot – RabbitMQ Publisher
 Spring Boot – RabbitMQ Consumer
 Spring Boot – SOAP Consumer
 Spring Boot – Soap WebServices
 Spring Boot – Batch Csv to Database
 Spring Boot – Eureka Server
 Spring Boot – MockMvc JUnit
 Spring Boot – Docker Deployment