Spring Boot框架中的条件注解,用于控制Bean的创建和配置。
@ConditionalOnClass
:当指定的类存在时,才会创建对应的Bean。例如:
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean
@ConditionalOnClass(MyDependency.class)
public MyBean myBean() {
return new MyBean();
}
}
只有当项目中包含MyDependency
类时,才会创建myBean
实例。
@ConditionalOnMissing
:当指定的属性不存在时,才会创建对应的Bean。例如:
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissing;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean
@ConditionalOnMissing(value = "my.property", havingValue = "true")
public MyBean myBean() {
return new MyBean();
}
}
只有当配置文件中没有my.property=true
这个属性时,才会创建myBean
实例。
@ConditionalOnProperty
:当指定的属性存在且满足指定的条件时,才会创建对应的Bean。例如:
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Bean
@ConditionalOnProperty(name = "my.property", havingValue = "true")
public MyBean myBean() {
return new MyBean();
}
}
只有当配置文件中存在my.property=true
这个属性时,才会创建myBean
实例。