I'm always excited to take on new projects and collaborate with innovative minds.
contact@niteshsynergy.com
https://www.niteshsynergy.com/
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.).
@Profile
OverviewThe @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.
We will demonstrate how to use @Profile
to register different cache managers for two profiles: dev and live.
dev
)ConcurrentMapCacheManager
.live
)EhCacheCacheManager
.Enable caching and component scanning using the following configuration:
For the dev
profile, use a simple cache manager (ConcurrentMapCacheManager
):
For the live
profile, configure an advanced cache manager (EhCacheCacheManager
):
You can activate profiles in several ways:
Activate profiles programmatically in a non-web application using the Spring context environment:
}
Alternatively, via a system property:
Using application.properties
or application.yml
in Spring Boot:
Add the following property in the application.properties
file
Or in application.yml
:
2. For a Servlet-based Application:
Add a context parameter to your web.xml
file (if applicable):
Activate a profile for unit tests using the @ActiveProfiles
annotation:
You can define profiles at the method level within a single configuration class:
You can enable multiple profiles simultaneously: