Spring Profiles Introduction

@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:


Profiles can be activates using different ways such as system property, annotation, web application context parameter etc. 


Different Ways to Activate Profiles

setActiveProfiles method

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

See example above.


spring.profiles.active context parameter

For a web application, we can define a context parameter in web.xml:



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:



System property

You can also activate profile using System property as:

System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dbprofile, fileprofile");

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!