Spring @Conditional 注解

前言

@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean。

接口

Conditional.java

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME) 
@Documented
public @interface Conditional {
    Class<? extends Condition>[] value();
}

Condition.java

public interface Condition {
    boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata);
}

将@Conditional加到创建Bean的类或方法上,指定Conditoin类的具体实现类,
就可以由具体的判断逻辑进行是否要创建Bean了。

默认实现

在org.springframework.boot:spring-boot-autoconfigure:[version] jar文件中的org.springframework.boot.autoconfigure.condition包中有如下常用的实现:

Condtion类Conditional注解说明
OnBeanCondition@ConditionalOnBeanMatches when beans meeting all the specified equirements are already contained in the BeanFactory
OnBeanCondition@ConditionalOnSingleCandidateMatches when a bean of the specified class is already contained in the BeanFactory and a single candidate can be determined
OnBeanCondition@ConditionalOnMissingBeanMatches when no beans meeting the specified requirements are already contained in the BeanFactory
OnClassCondition@ConditionalOnClassMatches when the specified classes are on the classpath
OnClassCondition@ConditionalOnMissingClassMatches when the specified classes are not on the classpath
OnCloudPlatformCondition@ConditionalOnCloudPlatformMatches when the specified cloud platform is active
OnExpressionCondition@ConditionalOnExpressionConfiguration annotation for a conditional element that depends on the value of a SpEL expression
OnJavaCondition@OnJavaConditionMatches based on the JVM version the application is running on
OnJndiCondition@ConditionalOnJndiMatches based on the availability of a JNDI InitialContext and the ability to lookup specific locations
OnPropertyCondition@ConditionalOnPropertyChecks if the specified properties have a specific value
OnResourceCondition@ConditionalOnResourceMatches when the specified resources are on the classpath
OnWebApplicationCondition@ConditionalOnWebApplicationMatches when the application is a web application
OnWebApplicationCondition@ConditionalOnNotWebApplicationMatches when the application is not a web application
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值