Spring Boot @Conditional annotation

The power of Spring Boot lies in the use of a new feature of the Spring 4 framework: the @Conditional annotation, which enables some configuration to be enabled only when certain conditions are met.

Let's introduce how to use Condition

to first write a class

package com.test.spring;  
  
import org.springframework.context.annotation.Condition;  
import org.springframework.context.annotation.ConditionContext;  
import org.springframework.core.type.AnnotatedTypeMetadata;  
  
public class MyCondition implements Condition  
{  
    /**
     * Write your own logic here. Only when true is returned, the configuration will be enabled
     */  
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata)  
    {  
        return true;  
    }  
}  


It's ready to use next

package com.test.spring;  
  
import java.io.Serializable;  
  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Conditional;  
import org.springframework.context.annotation.Configuration;  
  
@Configuration  
@Conditional(MyCondition.class)  
public class Config  
{  
    @Bean  
    public Serializable createSerializable()  
    {  
        System.out.println("======000");  
        return "";  
    }  
}  


The code @Conditional(MyCondition.class)
can be marked on the class, indicating that all @Beans under the class will enable configuration. It can

also be marked on the method, just enable the configuration for the method.



In addition to customizing the Condition itself, Spring also Provides a lot of Conditions for us to use

@ConditionalOnBean (a bean will only be instantiated when an object exists in the current context)
@ConditionalOnClass (a bean will be instantiated when a class is on the classpath)
@ConditionalOnExpression (when When the expression is true, a bean will be instantiated)
@ConditionalOnMissingBean (a bean will be instantiated only when an object does not exist in the current context)
@ConditionalOnMissingClass (when a class does not exist on the class path, A Bean will be instantiated)
@ConditionalOnNotWebApplication (not a web application)



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326097796&siteId=291194637