How to load Profile Specific Properties files in Spring Boot

Posted on

In this articles, we will see how to load Profile specific properties files from resource directory in Spring Boot application.

Here, we set up a sample Spring Boot Project and maintains set of configuration files specific to the Profile which would be loaded when the Application runs.

Total four configuration files are created in this sample Project:-

application.properties – Which is a parent property that always loaded first before Profile specific properties file.

application.${spring.profiles.active}.properties – This is a Profile specific properties file where ${spring.profiles.active} is a placeholder of any Env i.e DEV/UAT/PROD. This property file will be loaded right after parent properties. We can keep all Profile related configuration here additionally we can overwrite derived properties of parent property file.

spring.profiles.active – Spring provides this property to enabled active Profile which you have to provide in VM argument with Environment name.

-Dspring.profiles.active=dev

 

 

 

 

Here, we see Project setup hierarchy and configuration files created under resource folder ( /src/main/resources ).

 

 

 

 

 

 

 

 

 

application.properties file is parent properties file that contains all common properties which will be derived by Profile specifies properties file.

file.upload.size.limit =  1024
remote.connection.url=localhost
remote.connection.port=8080
remote.connection.username=user123
remote.connection.password=Pa$$wOrd


remote.https.enabled = false
remote.connection.auth=false

application-dev.properties  ( When application runs on DEV Profile then load all derived properties of application.properties file as well as it own properties )

env.name=dev

application-uat.properties ( When application runs on UAT Profile then Load and Overwrite properties value if it exists in parent properties file  )

file.upload.size.limit =  102400
remote.connection.url=220.120.56.80
remote.connection.port=9090
remote.connection.username=uatUser
remote.connection.password=UAT$123#

remote.https.enabled = true

env.name=UAT

application-prod.properties

file.upload.size.limit =  102400
remote.connection.url=220.110.56.63
remote.connection.port=9090
remote.connection.username=prodAdmin
remote.connection.password=Pa$$wOrd@233$

remote.https.enabled = true
env.name=PROD
remote.connection.auth=true

PropertiesUtils.Java:- This Utilities Class load all properties file in specified order means first it loads application.properties then load Profile specifies properties ( application.${spring.profiles.active}.properties ).

/**
 * Created by MYPC on 8/4/2017.
 */

package com.spring.example.utils;

        import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
        import org.springframework.core.io.ClassPathResource;
        import org.springframework.core.io.Resource;

        public class PropertiesUtils {

            public static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";

            public static void initProperties() {
                String activeProfile = System.getProperty(SPRING_PROFILES_ACTIVE);
                if (activeProfile == null) {
                    activeProfile = "dev";
                }
                PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer
                        = new PropertySourcesPlaceholderConfigurer();
                Resource[] resources = new ClassPathResource[]
                        {new ClassPathResource("application.properties"),
                                new ClassPathResource("application-" + activeProfile + ".properties")};
                propertySourcesPlaceholderConfigurer.setLocations(resources);

            }
        }

Finally, Main class which read all properties file and print on the Console.


package com.spring.example;

import com.spring.example.utils.PropertiesUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * list
 * Created by AJAY KUMAR on 1/9/2017.
 */
@SpringBootApplication
public class MainApplication {

    @Value("${file.upload.size.limit}")
    private long size;

    @Value("${remote.connection.url}")
    private String remoteConnectionUrl;

    @Value("${remote.connection.port}")
    private int remoteConnectionPort;

    @Value("${remote.connection.username}")
    private String remoteConnectionUsername;

    @Value("${remote.connection.password}")
    private String remoteConnectionPassword;

    @Value("${remote.https.enabled}")
    private String remoteHttpsEnabled;

    @Value("${env.name}")
    private String envName;

    @Value("${remote.connection.auth}")
    private String remoteConnectionAuth;

    public static void main(String[] args) {
        PropertiesUtils.initProperties();
        ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);
        MainApplication mainApplication = context.getBean(MainApplication.class);
        printEnvironmentsProperties(mainApplication);
    }

    private static void printEnvironmentsProperties(MainApplication MainApplication) {
        StringBuilder stringBuilder = new StringBuilder("Properties Files ......\n");

        stringBuilder.append("env.name").append(" : ").append(MainApplication.envName).append("\n")
                .append("file.upload.size.limit").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.url").append(" : ").append(MainApplication.remoteConnectionUrl).append("\n")
                .append("remote.connection.port").append(" : ").append(MainApplication.remoteConnectionPort).append("\n")
                .append("remote.connection.username").append(" : ").append(MainApplication.size).append("\n")
                .append("remote.connection.password").append(" : ").append(MainApplication.remoteConnectionPassword).append("\n")
                .append("remote.connection.auth").append(" : ").append(MainApplication.remoteConnectionAuth).append("\n")
                .append("remote.https.enabled").append(" : ").append(MainApplication.remoteHttpsEnabled).append("\n");
        System.out.println(stringBuilder.toString());
    }
}

By default, spring-profiles-active is dev Profile either you set active profile to dev or not, it loads application-dev.properties and give below output-

2017-08-05 17:37:35.068 INFO 11548 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.457 seconds (JVM running for 5.036)
Properties Files ……
env.name : dev
file.upload.size.limit : 1024
remote.connection.url : localhost
remote.connection.port : 8080
remote.connection.username : 1024
remote.connection.password : Pa$$wOrd
remote.connection.auth : false
remote.https.enabled : false

When you set spring-profiles-active is PROD  in VM options then you will get below output.

2017-08-05 17:41:06.539 INFO 10184 — [ main] com.spring.example.MainApplication : Started MainApplication in 4.095 seconds (JVM running for 4.783)
Properties Files ……
env.name : PROD
file.upload.size.limit : 102400
remote.connection.url : 220.110.56.63
remote.connection.port : 9090
remote.connection.username : 102400
remote.connection.password : Pa$$wOrd@233$
remote.connection.auth : true
remote.https.enabled : true

I hope this article would be helpful!! Thanks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s