Spring Profiles – @Profile Annotation and XML Configuration

In application development, sometimes we should make different configuration for each environment. Spring Profiles provides a way to separate application configuration into some parts and they are only available in one or more specific environments.

This tutorial introduces ways to use Spring Profiles by @Profile Annotation or XML Configuration.

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE (It’s OK if you use Eclipse)

II. Overview
1. Project Structure

springprofiles-structure
– Our application will have two main profiles: development and production.
– Depending on which profile is active, we will get corresponding @Bean Data.
– In class AppConfig, we also apply @Profile annotation for methods.
– To activate a profile, we use Environment#setActiveProfiles(profile) method.
– Instead of using @Profile annotation, we can declare profiles by XML.

2. Step to do

– Create Maven project
– Add Dependencies & Plugins
– Create Classes for Beans
– Create Configuration Class for each Profile
– Create Configuration Class for Application
– Create MainApplication Class
– Run Application & Enjoy Result

III. Practice
1. Create Maven project

– Open Spring Tool Suite, on Menu, choose File -> New -> Maven Project.
– Check Create a simple project, choose Workspace Location and click Next.
– Fill all fields in Artifact group box, then click Finish.

2. Add Dependencies & Plugins

Open pom.xml, add:

3. Create Classes for Beans

Under package bean, create 3 classes:

Data.java

Method.java

NewMethod.java

4. Create Configuration Class for each Profile

Under package config.data, create interface DataConfig and two implementation classes:

DataConfig.java

DevelopmentDataConfig.java

ProductionDataConfig.java

5. Create Configuration Class for Application

Under package config, create AppConfig.java:

AppConfig.java

6. Create MainApplication Class

MainApp.java

We set a Profile to be active by Environment from Context:

Another way to make a profile active is using System#setProperty method:

7. Run Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Java Application
– Check results in Console Screen:

8. XML Configuration for Profiles

Instead of using Spring Java Annotation, we can do those things by corresponding XML Configuration:

development_config.xml

production_config.xml

Two XML configuration files above will be imported to app_config.xml under :

So, to load XML Configuration with Profiles, the code inside function main should be changed to:

IV. Source Code

springprofile

By JavaSampleApproach | October 11, 2016.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*