The @configurationproperties annotation, which you should have known in the previous article, is enough to show you how to flexibly read ConfigurationProperties using the @configurationproperties annotation. This article will show you how to configure Spring beans flexibly

Writing in the front

When building a Spring application, we sometimes want to load a bean into the application context only when certain conditions are met. In Spring 4.0, we can do this with the @Conditional annotation

We see that the @Conditional annotation takes a generic class of the extends Condition interface, that is, to use the @Conditional annotation, we simply need to implement the Condition interface and rewrite its methods:

The matches method returns a Boolean, similar to our custom Validation annotation, which checks whether the specified criteria are met. Also note, the above notes and interface in the org. Springframework. Context. The annotation in the package

Finally came the age of Spring Boot, where Spring Boot was refined on the basis of @Conditional annotations, without the need to present complex letters of recommendation (implementing the Condition interface), Just hand your ticket with the pre-defined @conditionalonxxxx stamp and, if verified, walk into the Application Context lobby

Annotations,

Spring Boot to @ Conditional comments for us to do the refinement, these annotations are defined in the org. Springframework. Boot. Autoconfigure. Condition under the package

Opening the 13 annotations one by one, we found that they all had the same meta-annotation:

From these markers we can learn the following:

  • Can be applied to TYPE, that is, Spring automatically scans all classes (@Configuration, @Component, @Service, @repository, Or@controller) can be checked by adding the corresponding @conditionalonxxxx

  • Can be applied to methods, so methods with the @bean tag can also apply these annotations

  • All of them are marked with @conditional annotations, and custom conditions such as OnBeanCondition still implement the Condition interface. There is nothing mysterious about it, but more concrete encapsulation is done.

In fact, you can already understand the meaning of these notes from the literal meaning of these notes, but we still want to explain the specific use and some precautions, I will explain in descending order according to the frequency of personal use:

@ConditionalOnProperty

This note is no doubt at the top of the list

The conditional interpretation is: Properties or application. Yml file mybean.enable is true and MyCondition will be loaded if there is no match. Because matchIfMissing = true, the default is false.

@ ConditionalOnBean and ConditionalOnMissingBean

The @conditionalonbean annotation is sometimes used to load a Bean that already has an application context:

In contrast, sometimes we need a Bean to be loaded if it does not exist in the application context, so we use the @conditionalonmissingBean annotation

@ ConditionalOnClass and @ ConditionalOnMissingClass

Don’t be ridiculous, it’s the same as above, but it’s not too much to say if a class exists in the classpath

@ConditionalOnExpression

If we have more complex configuration attributes together, we can use this expression:

The MyModule is loaded only when both properties are true. The @configurationProperties annotation should be set to “true”. If no value is set for the property, the default value is set to true. This is the @vaue annotation specification, where all SpEL can be applied.

Write this, I have used up, but also brave to introduce a few other content 😄, a joke, we continue:

@ConditionalOnSingleCandidate

This comment is similar to @conditionalonbean, but to better illustrate the usage of this annotation, I will have to translate the class comment

A single candidate will be matched only if the specified class already exists in the BeanFactory and it can be determined

BeanFactory has multiple bean instances, but if a primary candidate is specified (usually using the @primary annotation on the class), it will also match. Essentially, if the auto-join matches a bean with a defined type, it succeeds

Currently, the condition only matches the bean definition that has already been processed by the application context. In itself, it is strongly recommended to use this condition only in the Auto-Configuration class. If the candidate bean is created by another Auto-Configuration, Make sure that those using this condition run after it

@ConditionalOnResource

We can use this annotation if the bean we are loading depends on whether or not the resource exists in the classpath

Isn’t it nice to see that logback.xml can add a similar switch when we introduce a third party toolclass like Dozer

What follows is a real surprise, and you get the impression that you can at least think of flexible configuration with these annotations if you need them

@ConditionalOnJndi

The bean is loaded only after the specified resource is loaded through JNDI

@ConditionalOnJava

Beans are loaded only if you are running the specified version of Java

@ ConditionalOnWebApplication and @ ConditionalOnNotWebApplication

This bean is loaded only when running in a Web application

In contrast, beans are loaded in a non-Web environment

@ConditionalOnCloudPlatform

The annotation of cold I have to stop breathing, only run on the specified cloud platform loads the specified bean, CloudPlatform is org. Springframework. Boot. Under the cloud of an enum type class, everyone can open to see:

That’s it, but not the end of Spring Boot’s 13 notes. Here are some cool things you need to know:

Combination conditions

Combination condition AND

If we want to apply multiple conditions together, and the relationship between the conditions is and, all we need to do is use @conditionalonxxxx on the class. Of course, we can also inherit AllNestedConditions class to encapsulate our multiple conditions

This gives you the combined and condition, and the specified bean is loaded only when all the internal conditions are met

Combination condition OR

What if we want the combination condition to be an OR relation? We can do this by inheriting AnyNestedCondition. The sample code is the same as above. You can open the AnyNestedCondition class and see the class description

Conditional combination NONE

If there is and and or, there must be non. We can do this by inheriting NoneNestedConditions

Custom annotations

The logic of multiple conditions can be applied in combination mode. If we need to apply these combination conditions, we also need to customize the annotations. In fact, as described in the beginning of this article, we can just write the built-in 13 annotations:

Just specify our custom Condition class via the @Conditional annotation, and then apply it where you want to use it

RabbitMq’s RabbitAutoConfiguration class is a good way to use these annotations:

Github.com/spring-proj…

conclusion

Now that you’ve seen how beans can be configured flexibly, I’m sure the definition will be more flexible based on previous articles. Open up your IDE and check out these annotations for more details

Soul asking

  1. SpringBoot adds a Web starter. What are some ways to change it to a non-Web application?
  2. Java8 Stream also has findAny, findAll and other operations.
  3. If there is no MyBean class in the classpath, the compiler will report an error.
@configuration@conditionalonClass (mybean.class) public class MyConfiguration{// omitted} ' '## improve efficiency tool! [](http://rgyb.sunluomeng.top/%E5%85%AC%E4%BC%97%E8%B4%A6%E5%8F%B7%E6%96%87%E7%AB%A0/%E6%84%9F%E6%83%B3%E4%B8%8E%E6%80%B BB E7% % % B 93 / _image / 2019-06-18 / p. ng) -- -- -- -- -- -- -- - # # recommended reading + [the red-black tree, super activity graph explanation, Simple] (https://mp.weixin.qq.com/s/ilND8u_8HGSTSrJiMB4X8g) + [parents delegation model: Giant high-frequency interview question, the easier] (https://mp.weixin.qq.com/s/Dnr1jLebvBUHnziZzSfcrA) + [the interview also don't know the difference between the BeanFactory and ApplicationContext?] (https://mp.weixin.qq.com/s/YBQB086ADBjHUmwrFQrWew) + [how to design a good RESTful API] (https://mp.weixin.qq.com/s/hR1TqkVzwZ_T8fuMnsM4hQ) + / program apes: why do you want to see the source code? (https://mp.weixin.qq.com/s/V7h8O6pVFQ-nr_iA2SNqtw) -- -- -- -- -- -- -- -- > # # # # welcome continuous attention to the public: "Multithreading" and "ElasticSearch" will be released in the future ** > to read the detective novel thinking easy fun learning Java technology stack related knowledge, in line with the principle of simplification of complex problems, abstract problems concrete and graphical gradually decompose technical problems, technology continues to update, please continue to pay attention to...... ! [](http://rgyb.sunluomeng.top/%E5%85%AC%E4%BC%97%E8%B4%A6%E5%8F%B7%E6%96%87%E7%AB%A0/%E6%84%9F%E6%83%B3%E4%B8%8E%E6%80%B B%E7%BB%93/_image/2019-06-18/a%20%281%29.png)Copy the code