Spring profile allows conditional registration of beans/components in runtime based on constants specified declaratively in configuration or programmatically in code. Let see some use cases.
Activate @Component based on active profile
Suppose we have a service interface called SomeService
which has a method called doSomething
:
1 | // In SomeService.java |
SomeService
should only do real work in production environment and trivials in others. We can do this way:
1 | // In SomeServiceImpl.java |
1 |
|
Now, based on whether production
profile is declared or not, SomeServiceImpl
or NoOpSomeServiceImpl
will serve requests as SomeService
.
Register @Bean based on active profile
1 |
|
A bean with type CustomBean
will be registered if profile dev
is active or featureA
is not active.
Testing accepted profiles through Spring Environment
Sometimes, it is considered be too heavy to switch whole bean/component based on active profile. We can use spring environment to test accepted profile.
1 | import org.springframework.core.env.Environment; |
If you are using Thymeleaf, you can do this:
1 |
|
Now, we knows how to use profile, let dig how to declare it.
Declare Spring profile in configuration file
In Spring Boot, you can declare profiles in application.properties
or application.yml
:
1 | spring.profiles.active = dev,featureA |
If you declare profiles this way, profiles specified outside application jar will override profiles inside application jar. If you want to declare a profile which can’t be overrode, use spring.profiles.include
.
1 | // application.properties inside projectA's jar |
application.properties
is just one of places to specify spring configuration, you can delcare profiles in other places according to Spring Boot Externalized Configuration. Such as:
1 | # os environment |
Specify profiles programmatically
In application level, you can add profiles using SpringApplication.setAdditinalProfiles
.
1 |
|
In library level, you can add/set profiles through ConfigurableEnvironment
.
1 | public class FeatureConfig implements ApplicationContextInitializer<ConfigurableApplicationContext> { |
1 | // In library's META-INF/spring.factories |