Spring @Conditional 注解

@Conditional 有条件的注解

当我们希望某个Bean满足了一定的条件才会被创建的时候,我们就可以使用@Conditional注解(Spring 4引入)来实现这种功能。该注解可以用到带有@Bean注解的方法上,如果给定的条件计算结果为true,就会创建这个bean,否则的话,这个bean会被忽略。

与这相关的注解有

  • @ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean)
  • @ConditionalOnClass(某个class位于类路径上,才会实例化一个Bean)
  • @ConditionalOnExpression(当表达式为true的时候,才会实例化一个Bean)
  • @ConditionalOnMissingBean(仅仅在当前上下文中不存在某个对象时,才会实例化一个Bean)
  • @ConditionalOnMissingClass(某个class类路径上不存在的时候,才会实例化一个Bean)
  • @ConditionalOnNotWebApplication(不是web应用)

该注册的bean 实现Condition 返回true 就表示可以创建

public interface Condition {

    /**
     * Determine if the condition matches.  确定条件是否匹配。
     * @param context the condition context
     * @param metadata metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
     * or {@link org.springframework.core.type.MethodMetadata method} being checked.
     * @return {@code true} if the condition matches and the component can be registered
     * 如果条件匹配,组件可以注册
     * or {@code false} to veto registration. 否决登记。
     */
    boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

}

//项目示例
 @Bean
 @ConditionalOnMissingBean
 public LogBuffer logBuffer(){
      return new LogBuffer();
 }

参考网站地址 https://blog.csdn.net/Zheng_junming/article/details/78230050

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值