1. 首页
  2. 软件开发
  3. Spring——条件化Bean注册的注解汇总

Spring——条件化Bean注册的注解汇总

  • 发布于 2024-08-17
  • 0 次阅读

在Spring框架中,与条件化Bean注册相关的注解主要包括以下几种:

  1. @ConditionalOnBean:当容器中存在指定Bean时,才会注册当前Bean。
  2. @ConditionalOnMissingBean:当容器中不存在指定Bean时,才会注册当前Bean。
  3. @ConditionalOnClass:当指定的类在类路径上存在时,才会注册当前Bean。
  4. @ConditionalOnMissingClass:当指定的类在类路径上不存在时,才会注册当前Bean。
  5. @ConditionalOnProperty:根据配置文件中的属性值来决定是否注册Bean。
  6. @ConditionalOnExpression:根据SpEL表达式的结果来决定是否注册Bean。

代码如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

@Configuration
public class AppConfig {
   

    @Bean
    @ConditionalOnBean(name = "myDependencyBean")
    public MyBean myBean() {
   
        return new MyBean();
    }

    @Bean
    @ConditionalOnProperty(name = "myapp.feature.enabled", havingValue = "true")
    public MyFeatureBean myFeatureBean() {
   
        return new MyFeatureBean();
    }
}

@ConditionalOnBean注解表示只有当名为"myDependencyBean"的Bean存在时才会注册MyBean;@ConditionalOnProperty注解表示只有当配置文件中myapp.feature.enabled属性值为true时才会注册MyFeatureBean。

原文链接: https://blog.csdn.net/2401_82884096/article/details/137939085