Engineering Full Stack Apps with Java and JavaScript
@Profile annotation allow you to register components that will be selected only if its associated profile is active. You can selectively activate a set of beans in a class or all beans .
You can have @Profile at bean level over @Bean or a configuration class level (with @Configuration). You may group different set of beans into different configuration files and apply different profiles. You can also specify @Profile along with @Component. If you are using an xml configuration, you can use the beans element along with its attributes profile and primary.
You can specify the profile name as "default" to enable it as default:
@Profile({"default","dbprofile"})
Profiles can be activates using different ways such as system property, annotation, web application context parameter etc.
setActiveProfiles method
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("fileprofile");
See example above.
spring.profiles.active context parameter
For a web application, we can define a context parameter in web.xml:
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dbprofile</param-value>
</context-param>
spring.profiles.active property
For a Spring boot application, we can define a property 'spring.profiles.active' in application.properties file. For non-boot spring applications, we can set the property in any properties file and then import the propertie file using @PropertySource on your Java configuration class.
@ActiveProfiles annotation
From within JUnit tests, we can enable profile using @ActiveProfiles:
@ActiveProfiles("dbprofile")
System property
You can also activate profile using System property as:
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dbprofile, fileprofile");