Profiles - Spring Boot

Amila Iroshan
The Fresh Writes
Published in
7 min readMay 5, 2023

Introduction

In this article, I’ll explain how to use profiles with Spring Boot application.

What are Spring Profiles ?

Profiles are the way of grouping the configuration properties into profiles and provide it into different environments like local/development , staging(QA/UAT/Pre-live) and production environment.

In briefly Profiles help to have different application configuration for different environments.

Why we use Spring Profile ?

The application development process has different stages like development, testing and production.

Application Development Process

Usually we have set of environment specific configuration settings with application and when we deploy application on different environments
there are certain things that are changing based on the deploying environment.
Most of the time the developer or devops engineer have a responsibility to changing those settings manually and proceed the deployment.
To overcome the such kind of annoying work Spring Boot introduced tool/technique called Profiles.

How we use Spring Profile ?

Spring boot introduced some dedicated file system which is profile-specific properties files. There are mainly two types

# application.properties
# application.yml

In here I’m going to use .yml file structure because of that it Contains key and value pairs. Besides that it Supports hierarchical structure.
So that it is easy to read and avoid code redundancy.

Example of .yml

profile:
qa:
url: http://qa.com
database: qaDB
prod:
url: http://prod.com
database: prodDB

Example of .properties

profile.qa.url=http://qa.com
profile.qa.database=qaDB
profile.prod.url=http://prod.com
profile.prod.url=prodDB

Note : You can see above .properties file specify that ‘profile’ in four times and ‘qa’ in two times. This kind of non-hierarchical/flat structures are very tedious to maintain.

Then Spring Boot allows to create profile specific property files in the form of application-{profile}.properties/yml.

application.properties / yml
application-development.properties / yml
application-qa.properties / yml
application-prod.properties / yml

The functioning of property files in application

Spring Boot properties are loaded in a particular order. By default, an application.properties/yml file is loaded and where it found in the root of the classpath or next to the executable JAR. Then the configuration properties in this file will be available in the Spring Boot application context. But when we specify active profile, then the default profile properties overridden by the properties of active profile. Specially we can use default profile to keep common/unchanged configurations.

The ways of setting the active profiles.

1). Enabling active profile in property file

Use in application.properties.

spring.profiles.active=prod

Or if you use .yml

spring:
profiles:
active: prod

2). Run .jar file with command line arguments

java -jar appname.jar — spring.profiles.active=dev OR

java -Dspring.profiles.active=dev -jar appJARname.jar

3). Via Environment Variable

export SPRING_PROFILES_ACTIVE=dev
java -jar profiles-0.0.1-SNAPSHOT.jar

4).Direct set it to main class via programmatically.

The org.springframework.boot.SpringApplication class has method called setAdditionalProfiles and it accept the array of active spring profiles at runtime.

@SpringBootApplication
public class ProfilesApplication {

public static void main(String[] args) {
SpringApplication application =
new SpringApplication(ProfilesApplication.class);
application.setAdditionalProfiles("dev");
application.run(args);
}

}

The ways of read the property files ?

  1. @Value

@value annotation is one of the simple approaches to read values directly from property files placed in the classpath in java.

@Value("${profile.qa.database}")
private String qaDatabase;

2. @PropertySource

@PropertySource annotation is used for adding property sources to the environment. This annotation is used with @Configuration classes.

Note : By default, @PropertySource doesn’t load YAML files. So if you want to load .yaml file with @PropertySource you have to provide the custom implementation of the PropertySourceFactory, which will handle the YAML file processing. Below code snippet describes it,

public class YamlPropertySource implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(resource.getResource().getFilename(), properties);
}
}

Besides that you have to specify the below annotations also.

@Configuration
@ConfigurationProperties(prefix = "yaml")
@PropertySource(value="classpath:application-credential.yml",factory = YamlPropertySource.class)
public class MyDataSourceConfiguration {

@Bean
public MyDataSource generateMyDataSource(@Value("${datasource.mysql.username}") String userName,@Value("${datasource.mysql.password}") String password) {

MyDataSource myDataSource =new MyDataSource();
myDataSource.setUserName(userName);
myDataSource.setPassword(password);
System.out.println("My Datasource UserName:"+userName);
System.out.println("My Datasource Password:"+password);
return myDataSource;
}
}

The usages of @Profile in spring boot

Why we use @Profile ?

By using @Profile annotation, we can control the beans which are loaded into Spring’s application context at runtime according to it’s active profile.
If the profile is not active, there will be no Bean instance available in the application context.

For demonstration purposes I’ll do some simple exercise.

Just assume that we have to integrate life insurance with our application and we have set of life insurance providers like CeylincoLife, AIA and Allianz. Then we are going to make a interface called LifeInsurance and then implement purchacePolicy method in each life insurance provider classes. After that if we auto wired the LifeInsurance interface and called the purchacePolicy method ,the compiler will get ambiguity which bean would it be inject.

Usually we can resolve this kind of ambiguity by using @Primary or @Qulifier annotation. Which specify that exact bean to inject.

But if we want to inject particular bean according its environment we can use @Profile.

public interface LifeInsurance {
public void purchacePolicy(String environment);
}
@Component
@Profile("prod")
public class AIAInsuranceProvider implements LifeInsurance{
@Override
public void purchacePolicy(String env) {
System.out.println("Thank You For Purchase AIA Insurance @ " + env );
}
}
@Component
@Profile("uat")
public class AllianzInsuranceProvider implements LifeInsurance {
@Override
public void purchacePolicy(String env) {
System.out.println("Thank You For Purchase Allianz Insurance @ " +env);
}
}
@Component
@Profile("dev")
public class CeylincoLifeInsuranceProvider implements LifeInsurance {
@Override
public void purchacePolicy(String env) {
System.out.println("Thank You For Purchase CeylincoLife Insurance @ " +env);
}
}
@SpringBootApplication
public class SpringProfilesApplication implements CommandLineRunner {

@Value("${profile.qa.database}")
private String qaDatabase;

@Value("${application.environment.name:my default value}")
private String environmentName;

@Autowired
private LifeInsurance lifeInsurance;

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

@Override
public void run(String... args) throws Exception {
System.out.println("Name of the QA database : " + qaDatabase);
lifeInsurance.purchacePolicy(environmentName);
}

When run above application by providing the specific profile it will inject particular bean to application context according the given profile.

Result

This is the brief detail article of Profiles in Spring Boot. If you need deep dive on spring profiles please read — https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.external-config

Thank you for read this article and If you like this article, do follow and clap 👏🏻.Happy coding, Cheers !!😊😊

You can find the complete code for this example on my GitHub

Do support our publication by following it

--

--

Amila Iroshan
The Fresh Writes

Software Engineer | Open Source Contributor | Tech Enthusiast