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
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)