Use of Spring @Conditional annotations

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.

Here's how to use Condition

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 "";  
    }  
}  

@Conditional(MyCondition.class)

This code 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 that method

In addition to customizing Conditions by ourselves, Spring also provides many Conditions for us to use

@ConditionalOnBean (a bean will be instantiated only when an object exists in the current context)
@ConditionalOnClass (a bean will be instantiated when a class is on the classpath)
@ConditionalOnExpression (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 (a bean will be instantiated when a class does not exist on the class path)
@ConditionalOnNotWebApplication (not a web application)

 

Guess you like

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