Spring Profiles
Sometimes, we fall in a need of applying conditions for bean creations based on several environments (prod, qa, dev etc.). In other words, we create beans with different values depending on environments. This is known as defining different profiles in Spring framework and loading beans according to profile.
We feel the need of profiles when we start to maintain workflows for several environments. I will demonstrate how we can achieve it in both Spring framework and Spring Boot.
Spring Framework
To use profiles in Spring Framework we have to do the following things.
a) We will write configuration in onStartup() method of our AppInitializer class.
rootContext.getEnvironment().setActiveProfiles(“prod”); // dev | qa| prod etc
b) Let’s assume, we are applying profile only for HibernateConfig class. In this case, we will have to clone our existing hibernate.properties file and create hibernate-dev.properties, hibernate-prod.properties files.
c) Now we will have to change the HibernateConfig file for using appropriate profile.
i. Autowire Environment instance in HibernateConfig.
@Autowired
private Environment environment;
ii. Load appropriate properties file while creating SessionFactory bean.
Properties settings = getProperties("hibernate-"+environment.getActiveProfiles()[0]+".properties");
The complete source code will be found here.
Spring Boot
For Spring Boot, profiling is much simpler. We only need to create separate profile specific properties files.
Then we need to tell the application which profile we are willing to use in our application.properties file.
spring.profiles.active=dev
It will load the dev profile specific properties.
Now run the application. If the application starts without any exception, go to your browser and hit http://localhost:8080/
If you see Test passed in your browser, you can know that your profile is working.
The complete source code for this can be found here.