Some people saied that Java is too old to use, but every few years there always will be a hero who will make Java brand new again. Last time it was Spring, this time Spring Boot. In this blog we will talk about the most important feature in Spring Boot: Conditional annotation.
Foreword
Some people saied that Java is too old to use, but every few years there always will be a hero who will make Java brand new again. Last time it was Spring, this time Spring Boot. In this blog we will talk about the most important feature in Spring Boot: Conditional annotation.
What’s Conditional Annotation?
Conditional annotation already existed in Spring 4, It is used to develop an “If-Then-Else” type of conditional checking for bean registration, it’s just like a more generalized version of @Profile annotation. The difference is @Profile is used to write conditional checking based on Environment variables only, but @Conditional allows Developer to define user-defined strategies for conditional checking. @Conditional can be used for conditional bean registrations, that’s a main point that contribute to Spring Boot’s auto config.
How to use?
- First we can see how to use in Spring: import spring-context:
1 | <dependencies> |
- Then define an interface Food:
1 | public interface Food { |
- And we have Rice and Noodles to implement Food:
1 | public class Rice implements Food { |
- In China, the people from north like to eat noodles as the main food, and the south like to eat rice, we use this to create condition:
1 | public class NoodlesCondition implements Condition { |
- Then the Java config:
1 |
|
- Now we can test in main method:
1 | public class Main { |
- This is Spring’s Conditional annotation, it can create different bean based on the property of environment.
What’s more
Profile is a special conditional annotation, we usally use it to swithing between dev and pro environment, still the same example:
1 |
|
We can load Bean like this:
1 | public class Main { |
Conclusion
We can see that @Profile is more convenient to use, but @Conditional is more flexible, if you read the source code you will find @Profile is a special @Conditional, they are all used for checking if the context satisfy a certain condition, and then create a certain Bean, this feature support the auto config of Spring Boot.