Spring boot is powerful because it uses the new features of the Spring 4 framework: @Conditional annotations, which enable some configurations only if 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 return true to enable configuration */
public
Boolean Matches (Conditioncontext context, annotatedtypemetadata Metadata)
{
return true;
}
}
The next step is to use the
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 labeled on the class, indicating that all @bean under the class are enabled for configuration
can also be labeled on the method, just enable configuration for the method
In addition to your own custom condition, Spring provides a lot of condition for us
@ConditionalOnBean (a bean is instantiated only if an object exists in the current context)
@ConditionalOnClass (a class is located on the classpath to instantiate a bean)
@ConditionalOnExpression (a bean is instantiated only when the expression is true)
@ConditionalOnMissingBean (a bean is instantiated only if an object does not exist in the current context)
@ConditionalOnMissingClass (a bean is instantiated only if it does not exist on a class path)
@ConditionalOnNotWebApplication (not web App)