0

Using @Conditional with @Configuration in Spring

Using @Conditional with @Configuration in Spring allows us to group @Bean objects that are loaded on a specific condition without resorting to using @Profile and too many @Bean/@Conditional.

Requirements

Stuff used for this post.

  • Spring Boot 2.0.4.RELEASE
  • JDK 8
  • IntelliJ IDEA

Grouping @Bean’s into Two

All-English Configuration

This @Configuration class contains all @Bean’s that give out String values in the English language.

The Condition implementation for this is as follows:

All-German Configuration

This @Configuration class contains all @Bean’s that give out String values in the German language.

The Condition implementation for this is as follows:

Main Class

To toggle between language, we explicitly set either one of the system properties – “english” or “german” – and run within the IDE.

Testing

Using “german” sytem property.

This is equivalent to -Dgerman=”any value”.

Using “english” sytem property.

This is equivalent to -Denglish=”any value”.

Download the codes

https://github.com/Turreta/Using-Conditional-with-Configuration-in-Spring

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert