Java, Software Development, Spring

Using @Conditional with @Configuration in Spring

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

Requirements

We used the following items for this post.

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

Grouping Beans into Two in Spring

1. All-English Configuration

The @Configuration class contains all beans that give out String values in English. For example, consider the following codes.

The Condition implementation for this is as follows:

2. All-German Configuration

This @Configuration class contains all beans that give out String values in the German language. Consider the following codes.

The Condition implementation for this is as follows:

Test @Conditional and @Configuration in Spring

To toggle between languages, we explicitly set either one of the system properties – “English” or “German” – and run within the IDE.

Then, we can test our codes by switching between languages using a property. For example, when we want to display a message in German, we could use the “German” system property, which is equivalent to -Dgerman="any value".

Meanwhile, when we want to display a message in English, we use the “English” system property. Also, this is equivalent to -Denglish="any value".

Download Spring @Conditional and @Configuration Sample Codes

For more information, please download the codes from this GitHub repository.

Loading

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