I'm always excited to take on new projects and collaborate with innovative minds.

Phone

+1 234 567 890

Email

contact@botble.com

Website

https://botble.com

Address

123 Main Street, New York, NY 10001

Social

Spring Boot Profile

Spring @Profile Overview
The @Profile annotation in Spring allows developers to conditionally register beans based on specific runtime conditions, such as the environment (development, staging, production) or the operating system (Windows, Linux, etc.).

Spring Boot Profile

Spring @Profile Overview

The @Profile annotation in Spring allows developers to conditionally register beans based on specific runtime conditions, such as the environment (development, staging, production) or the operating system (Windows, Linux, etc.).

This is particularly useful when you want to switch configurations or beans without changing code but based on an active profile.

Use Case: Conditional Cache Manager Registration

We will demonstrate how to use @Profile to register different cache managers for two profiles: dev and live.

Behavior

  1. Development Profile (dev)
    • Registers a simple cache manager: ConcurrentMapCacheManager.
  2. Live Profile (live)
    • Registers an advanced cache manager: EhCacheCacheManager.
       

Tools Used

  • Spring Boot: 3.3.5
  • Ehcache: 2.9.0
  • Java: 17
  • IDE: IntelliJ IDEA

1. Spring Boot Configuration and Profiles

1.1. General Configuration

Enable caching and component scanning using the following configuration:

 

image.png

 

1.2. Development Profile: Simple Cache Manager

For the dev profile, use a simple cache manager (ConcurrentMapCacheManager):

image-1.png
image-2.png

1.3. Production Profile: EhCache Cache Manager

For the live profile, configure an advanced cache manager (EhCacheCacheManager):

image-3.png
image-4.png
image-5.png

2. Activating Profiles

You can activate profiles in several ways:

2.1. Programmatically

Activate profiles programmatically in a non-web application using the Spring context environment:

image-6.png
image-7.png

}

Alternatively, via a system property:

image-8.png

2.2. Web Applications

  1. Using application.properties or application.yml in Spring Boot:

    Add the following property in the application.properties file

  2. image-9.png

    Or in application.yml:

    image-10.png

     

    2. For a Servlet-based Application:
    Add a context parameter to your web.xml file (if applicable):

    image-11.png
  3. 2.3. Unit Tests

  4. Activate a profile for unit tests using the @ActiveProfiles annotation:

    image-12.png
    image-13.png

     

  5. 3. Advanced Configurations

  6. 3.1. Method-Level Profiles

    You can define profiles at the method level within a single configuration class:

    image-14.png


     

    image-15.png
    image-16.png
  7. 3.2. Multiple Profiles

    You can enable multiple profiles simultaneously:

    image-17.png
2 min read
नव. 17, 2024
By Nitesh Synergy
Share