Spring Framework learning (seven): @ Conditional Notes: The cornerstone SpringBoot

If you read the first six articles, I believe you to configure Spring, Spring understand the core principles already have a basic knowledge. This series of articles is not interpreted Spring source code, but to understand how the Spring framework simplifies Java development. I think you would like me to have this feeling: Spring's comment too much, and how these annotations so much? .... In fact, the entire support behind the huge Spring Framework is a Java basics: reflection, design patterns, and so on. In fact, the annotation itself is not what is given to the program at runtime its meaning, yes, run-time, these annotations are basically to get through the reflection mechanism, and then to complete a logic based on this comment.

 

You certainly no stranger to SpringBoot, "out of the box, agreed greater than the configured" concept. In fact, SpringBoot entire underlying framework or Spring, simplifying the development of the idea, every thing should be considered in the framework of designers, who do not want to frame designed to be more simple? Do you know why SpringBoot can do "out of the box" it?

 

Spring has a powerful comment: @Conditional. From the literal meaning, you should know that this is a "condition" means. Yes, this annotation allows to create conditions for the bean, what does that mean? According to that condition is met to decide whether to create a bean. Of course, the light use this annotation has no effect, also need to specify parameters for the notes. @Conditional look at the source code.

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
    Class<? extends Condition>[] value();
}

Using this annotation should pass a Class object as a parameter, just like this: @Conditional (MyCondition.class) , this class is that you MyCondition class that implements the Condition interface, implement this interface to matches () method overrides, you can achieve your logic, this function returns a value determines whether to create annotations @Conditional bean, like this:

    @Bean
    @Conditional(MyCondition.class)
    MyBean myBean(){
        new MyBean()
    }

If the conditions are met, the bean is created, or not created. You can personally try it and see how to write matches () method. "Spring combat Fourth Edition" is so written:

 

ConditionContext is a parameter matches () function. how? Do you see the shadow of SpringBoot?

About @Conditional notes introduced here, welcome comments, favorites, attention! Next article we explore Spring advanced assembly methods.

 

Guess you like

Origin www.cnblogs.com/chenyulin/p/11224074.html