New features of spring 4.0: @ conditional annotation details
preface
Recently, when learning spring, I will summarize the knowledge I have learned. In this article, we will touch the new function of spring 4: @ conditional annotation. In previous versions of spring, you can only handle conditions in the following two ways:
Let's look at the above two separately to understand the @ conditional annotation brought by spring 4.
Spring Expression Language(SPeL)
The ternary identifier of spiel (If-Then-Else) can be used to express conditional statements in the spring configuration file.
The properties of the bean depend on the value of flag, which is injected using external properties, so the bean has dynamic capability.
Using profiles
This was introduced in spring 3.1. Use it like this.
Use spring 4's @ conditional annotation
Now let's introduce the @ conditional annotation. The official document states that "components can be registered only when all specified conditions are met". The main use is to add a series of constraints when creating beans.
The conditional interface is declared as follows:
Therefore, the @ conditional annotation is used as follows
If a @ configuration class uses @ conditional, it will affect all @ bean methods and @ import associated classes
Here is an example
Here we have two classes: systempropertycondition and systempropertyabsentconnection Both classes implement the condition interface The overridden method returns a Boolean value based on the attribute flag.
Now we define two classes, one is a positive condition and the other is a negative condition:
The profiles mentioned above have been modified through the conditional prototype annotation.
summary
This article introduces the conditional annotation of spring 4. Note that the condition annotation is not inherited. If a parent class uses conditional annotations, its subclasses will not have conditions. If you try the above examples, it will help you get a better understanding.
Well, the above is the whole content of this article. I hope the content of this article can bring some help to your study or work. If you have any questions, you can leave a message. Thank you for your support for programming tips.