0

Spring Boot – How to use @Conditional in your own codes

This post demonstrates how to use the @Conditional annotation which is the workhorse of Spring Boot’s automatic configuration. You may also use this technique in your own codes.

First, there was @Profile

@Profile annotation allows for the registration of multiple beans of the same type and associate them to one or more profiles. When you run your application, you make one or more profiles active by

  • Listing them as comma-delimited string value in applications.properties file, e.g.,
  • Listing them as comma-delimited string value in web.xml (for web applications), e.g.,
  • Listing them as a System property

As you can see, there is no “intelligence” applied with @Profile.

Then came @Conditional

Spring introduced the @Conditional annotation in Spring 4 which allows for registration of beans conditionally based on any arbitrary condition.

Yes, in any arbitrary condition like whether or not Today is a public holiday!

Typical conditions to check

These are typically the conditions you want to base your bean creation on

  • whether or not a specific class is present in the classpath
  • whether or not a specific file exists on a location
  • whether or not a specific property value is configured in a configuration file
  • whether or not a system property value is available

The Condition Interface

Using @Conditional starts with the Condition interface:

It is an interface with a single method.

Sample Condition

Let’s create a Spring Boot Application

Let’s create a new Spring Boot Application using IntelliJ (optional) and Spring Initialzr (or http://start.spring.io/).

Step 1: Create a new project

Choose Spring Initialzr. Then click Next.

Step 2: Provide project information

Step 3: Choose nothing

Step 4: Save the new project

Step 5: Create our conditions

IsTodayFridayCondition class

This class checks whether or not Today is Friday.

ActiveEveryDayCondition class

This just makes the associated beans active everyday.

Step 6: Create our configuration class

POJOs needed

These are the classes needed for our configuration class.

EveryDayBean class

FridayOnlyBean class

MyConfig class

Here we used the @Conditional annotation for each @Bean

Step 7: Test our codes

You may download all the codes from the link provided at the very bottom section.

Unit Test Output

Download the Codes

https://github.com/Turreta/Spring-Boot-How-to-use-Conditional-in-your-own-codes

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert