in Spring

Spring Profiles Tutorial

Introduction

From Spring version 3.1 profiles are supported. This is a really nice feature that enables you to have environment specific beans wiring setuped in super easy way. In this tutorial I will show you how to leverage profiles spring feature. We will use  POJO Knight and two  implementations.

Spring XML Profiles setup

You saw that we have two implementations of Knight one to be used in production and other to be used in development environment. Lets see how to do that.

Observe tag <beans> and profile attribute, for dev profile spring will

  • create bean knight
  • use implementation DevelopmentKnight
  • set property knightName to be “Dev Knight”, here I have used p namespace to set the property.

For prod profile I want to use different implementation with different property value.

Note: Profile attribute can be set on root beans tag and on child beans tags as well.

 

Spring XML profiles demonstration

Here I am using ClassPathXmlApplicationContext to load the xml config, after this I set the active profile(s) and refresh the context. If you run this example you will see:

Dev Knight

Awesome!

Spring java profiles setup

Lets see how to wire our knights beans using java configuration. For this we need JavaConfig class with @Configuration annotation.

Spring java profiles demonstration

Here I will load prod profile and print class name of the injected bean.

As you see it is super easy to load annotation config application context and register correct configuration class.

Activate Spring profile

There are multiple ways to activate spring profile.

Programatically:

applicationContext.getEnvironment().setActiveProfiles("dev");

Declaratively:

-Dspring.profiles.active="dev"

web.xml

 

Unit Testing Spring profiles

Lets see how to test our profile setup. Here is the simple example that makes sure that all works .

To test xml configuration we will change the test in minor way like this

 

Spring is awesome, right ?

 

Write a Comment

Comment

Webmentions

  • Spring JPA Repositories tutorial – pscode.rs

    […] enabled so that you use one datasource for production and other for development like environments. This post can help you with spring […]