Software Development, Spring Boot

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

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



Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.

You Might Also Like