在Spring Boot 2中,我们可以使用@ConditionalOnProperty注解来控制配置属性,以决定是否创建某个Bean。
例如,如果我们想要根据配置文件中的属性feature.enabled来决定是否创建一个特定的Bean,我们可以这样做:
@Configuration
public class FeatureConfig {
 
    @Bean
    @ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
    public FeatureService featureService() {
        return new FeatureService();
    }
}在上述代码中,FeatureService这个Bean只会在application.properties或application.yml中配置了feature.enabled=true时才会被创建。
另外,@ConditionalOnClass和@ConditionalOnMissingClass注解可以用来根据类的存在或不存在来创建Bean。
@Configuration
public class ConditionalConfig {
 
    @Bean
    @ConditionalOnClass(name = "com.example.SomeClass")
    public SomeService someService() {
        return new SomeService();
    }
}在这个例子中,SomeService这个Bean只会在类路径中存在com.example.SomeClass类时才会被创建。
这些注解都是基于条件的注解,可以使用它们来控制Spring容器中Bean的创建,这在实际开发中是非常有用的。