In the world of Spring Boot, it’s important to grasp and make use of Spring Boot Profiles if you want to handle application environments well. Spring Boot profiles are like a key tool that lets you easily switch between different application settings, ensuring that your application can smoothly adjust to the needs of each particular environment. In this guide, we’ll explore the details of Spring Boot profiles and demonstrate how to use them to keep your configurations neat and ready for different environments, even if you’re new to this.
Table of Contents
Understanding Spring Boot Profiles
What Are Spring Boot Profiles?
In the context of Spring Boot, Spring Boot Profiles are a fundamental mechanism for handling environment-specific configurations. They empower developers to define and segregate configuration settings for different environments, such as development, testing, and production. Each profile encapsulates configuration values tailored precisely to the demands of a specific environment.
How Do Spring Boot Profiles Work?
Spring Boot Profiles operate on the foundation of the
annotation and a set of configuration classes. These profiles can be activated during application startup, enabling the Inversion of Control (IoC) container to intelligently select and deploy the appropriate configuration based on the active profile. This powerful capability eliminates the need for extensive code modifications when transitioning between different application environments.
Creating Spring Boot Profiles with Annotations
In this section, we’ll explore the creation and management of Spring Boot profiles using annotations. This approach provides a structured and flexible way to handle environment-specific configurations.
Step 1: Create Configuration Classes
Begin by crafting two distinct configuration classes: DevJavaConfig
and TestJavaConfig
. These classes extend the common BaseConfig
class and are adorned with the @Configuration
annotation. Additionally, they specify the property sources for their respective profiles.
@Configuration
@PropertySource("classpath:appdev.properties")
@Profile("dev")
class DevJavaConfig extends BaseConfig {
}
@Configuration
@PropertySource("classpath:apptest.properties")
@Profile("test")
class TestJavaConfig extends BaseConfig {
}
Step 2: Define Property Files
Next, define property files, namely application-dev.properties
and application-test.properties
. These property files contain the database and transaction manager properties tailored to the dev
and test
profiles.
application-dev.properties
file:
# application-dev.properties
db.driverClassname=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/sdb
db.username=root
db.password=root
tm.timeout=10
tm.autocommit=false
application-test.properties
file:
# application-test.properties
db.driverClassname=com.jdbc.driver.OracleDriver
db.url=jdbc:oracle:thin:@1521:xe
db.username=root
db.password=root
tm.timeout=10
tm.autocommit=false
Step 3: Set the Active Profile
In the application.properties file, set the active profile to test
as an example of profile activation.
spring.profiles.active=test
Step 4: Implement Configuration Classes
In the main application class BootProfileApplication
, configure the JdbcTransactionManager
bean based on the active profile. The @Bean
method injects properties using the Environment
bean.
@SpringBootApplication
class BootProfileApplication {
@Autowired
private Environment env;
@Bean
public JdbcTransactionManager jdbcTransactionManager() {
JdbcTransactionManager jtm = new JdbcTransactionManager();
jtm.setTimeOut(Integer.parseInt(env.getProperty("tm.timeout")));
jtm.setAutoCommit(Boolean.valueOf(env.getProperty("tm.autocommit")));
return jtm;
}
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(BootProfileApplication.class, args);
JdbcTransactionManager jtm = context.getBean(JdbcTransactionManager.class);
System.out.println(jtm);
}
}
Activating Spring Boot Profiles in Properties File
Alternatively, you can activate Spring profiles directly through the properties file. This approach simplifies the activation process and maintains a clean separation of configuration properties.
Step 1: Specify YAML Property Files with “Spring Profiles Active in YAML File”
In this approach, you define YAML property files for each profile (dev
and test
) with their respective configuration values.
---
spring:
profiles:
active: dev
---
spring:
profiles: dev
parcel:
parcelNo: 123
sourceAddress: 8485, idkew
destinationAddress: 903, kdldqq
agent:
agentNo: 100
agentName: AAA
mobileNo: "993"
emailAddress: "9939393abc@gmail.com"
---
spring:
profiles: test
parcel:
parcelNo: 199
sourceAddress: 9396, idksd
destinationAddress: 903, kdldqr
agent:
agentNo: 101
agentName: BBB
mobileNo: "969"
emailAddress: "96969696bcd@gmail.com"
Step 2: Integrate the Dependency into pom.xml
To enhance the configuration capabilities of your Spring Boot application, incorporate the following dependency into your project’s pom.xml
file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
Step 3: Instantiate the Agent Bean
// Source code is not available
public class Agent {
private int agentNo;
private String agentName;
private String mobileNo;
private String emailAddress;
// Constructors, getters, setters, and any additional methods will go here
}
Step 4: Implement the Parcel Class as Shown Below
@Component
@ConfigurationProperties(prefix = "parcel")
public class Parcel {
private int parcelNo;
private String sourceAddress;
private String destinationAddress;
@Autowired
private Agent agent;
}
Step 5: Configure the Application
In your Spring Boot application class BootProfileApplication
, create and configure the Agent
bean based on the active profile. The properties are obtained from the properties files using the Environment
bean.
@SpringBootApplication
class BootProfileApplication {
@Autowired
private Environment env;
// The source code is unavailable, necessitating the
//creation of a bean using the @Bean annotation.
@Bean
public Agent agent() {
Agent agent = new Agent();
agent.setAgentNo(Integer.parseInt(env.getProperty("agentNo")));
agent.setAgentName(env.getProperty("agentName"));
agent.setMobileNo(env.getProperty("mobileNo"));
agent.setEmailAddress(env.getProperty("emailAddress"));
return agent;
}
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(BootProfileApplication.class, args);
Parcel parcel = context.getBean(Parcel.class);
System.out.println(parcel);
}
}
- Build the Application: Make sure the Spring Boot application is built and ready for execution. This can typically be done using build tools like Maven or Gradle.
- Run the Application with a Specific Profile:
- To run the application with the
dev
profile, execute the following command in your terminal or IDE:
- To run the application with the
Spring Profiles Active Command line
java -Dspring.profiles.active=dev -jar target/your-application.jar
To run the application with the test
profile, use this command:
java -Dspring.profiles.active=test -jar target/your-application.jar
- Observe the Output: When the application starts, it will load the configuration specific to the active profile (
dev
ortest
). This includes database settings, transaction manager properties, and any other environment-specific configurations. - Review the Output: As the application runs, it may print log messages, information, or the state of specific beans (as indicated by the
System.out.println
statements in the code). These messages will reflect the configuration loaded based on the active profile.
For example, when running with the dev
profile, you might see log messages and information related to the dev
environment. Similarly, when using the test
profile, the output will reflect the test
environment’s configuration.
Example: When Executing the Application with the “dev” Profile, You Will Observe the Following Output:
Conclusion:
Spring Boot profiles enable the seamless configuration of applications for different environments by allowing you to maintain distinct sets of properties. Profiles are activated based on conditions such as environment variables or command-line arguments, providing flexibility and consistency in application configuration across various deployment scenarios.
For additional details about Spring Boot profiles, you can refer to the following link: Spring Boot Profiles Documentation
Related Articles:
It was very crisp and understandable, great job 👏😊