《SpringBoot系列十一》:精讲如何使用@Conditional系列注解做条件装配

简介: 《SpringBoot系列十一》:精讲如何使用@Conditional系列注解做条件装配

一、@Conditional简介和使用

@Conditional注解是从spring4.0版本才有的,其是一个条件装配注解,可以用在任何类型或者方法上面,以指定的条件形式限制bean的创建;即当所有条件都满足的时候,被@Conditional标注的目标才会被spring容器处理。

  1. @Conditional本身也是一个父注解,从SpringBoot1.0版本开始派生出了大量的子注解;用于Bean的按需加载。
  2. @Conditional注解和其所有子注解必须依托于被@Component衍生注解标注的类,即Spring要能扫描到@Conditional衍生注解所在的类,才能做进一步判断。
  3. @Conditional衍生注解可以加在类 或 类的方法上;加在类上表示类的所有方法都做条件装配、加在方法上则表示只有当前方法做条件装配。

1、@Conditional源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

    /**
     * All {@link Condition} classes that must {@linkplain Condition#matches match}
     * in order for the component to be registered.
     */
    Class<? extends Condition>[] value();

}
AI 代码解读

@Conditional注解只有一个value参数,类型是:Condition类型的数组;而Condition是一个接口,其表示一个条件判断,内部的matches()方法返回true或false;当所有Condition都成立时,@Conditional的条件判断才成立。

1)Condition接口

@FunctionalInterface
public interface Condition {

    /**
     * 判断条件是否匹配
     * @param context 条件判断上下文
     * @param metadata 注解元数据
     * @return 如果条件匹配返回TRUE,否者返回FALSE
     */
    boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

}
AI 代码解读

Condition是一个函数式接口,其内部只有一个matches()方法,用来判断条件是否成立的,方法有2个入参:

context:条件上下文,ConditionContext接口类型,用来获取容器中的信息
metadata:用来获取被@Conditional标注的对象上的所有注解信息

2)ConditionContext接口

public interface ConditionContext {

    /**
     * 返回bean定义注册器BeanDefinitionRegistry,通过注册器获取bean定义的各种配置信息
     */
    BeanDefinitionRegistry getRegistry();

    /**
     * 返回ConfigurableListableBeanFactory类型的bean工厂,相当于一个ioc容器对象
     */
    @Nullable
    ConfigurableListableBeanFactory getBeanFactory();

    /**
     * 返回当前spring容器的环境配置信息对象
     */
    Environment getEnvironment();

    /**
     * 返回正在使用的资源加载器
     */
    ResourceLoader getResourceLoader();

    /**
     * 返回类加载器
     */
    @Nullable
    ClassLoader getClassLoader();

}
AI 代码解读

ConditionContext接口中提供了一些常用的方法,用于获取spring容器中的各种信息。

2、@Conditional衍生注解使用案例

上面提到,从SpringBoot1.0版本开始@Conditional派生出了大量的子注解;用于Bean的按需加载。主要包括六大类:Class Conditions、Bean Conditions、Property Conditions、Resource Conditions、Web Application Conditions、SpEL Expression Conditions。见Spring Boot官网
在这里插入图片描述
它们的作用:

下面分开来看它们是怎么使用的:

1)Class Conditions

包含两个注解:@ConditionalOnClass 和 @ConditionalOnMissingClass。

1> @ConditionalOnClass

@ConditionalOnClass注解用于判断其value值中的Class类是否都可以使用类加载器加载到,如果都能,则符合条件装配。
在这里插入图片描述
@ConditionalOnClass注解中有两个属性:value() 和 name()。

  1. @ConditionalOnClass#value() 属性方法提供“类型安全”的保障,避免在开发过程中出现全类名拼写的低级失误。
  2. @ConditionalOnClass#name() 多用于三方库或高低版本兼容的场景

使用方式(参考源码中的WebClientAutoConfiguration类):

@ConditionalOnClass(WebClient.class)
@Configuration
ClientHttpConnectorAutoConfiguration.class })
public class WebClientAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,只有当WebClient.Class类和ClientHttpConnectorAutoConfiguration.class类都存在时,才会加载WebClientAutoConfiguration到Spring容器。

2> @ConditionalOnMissingClass

@ConditionalOnMissingClass注解用于判断其value值中的Class类是否都不可以使用类加载器加载到,如果都不能,则符合条件装配。

使用方式:

@ConditionalOnMissingClass("org.aspectj.weaver.Advice")
@Configuration
static class ClassProxyingConfiguration {
    ....
}
AI 代码解读
  • 这里表示,只有当org.aspectj.weaver.Advice类不存在时,才会加载ClassProxyingConfiguration到Spring容器。

2)Bean Conditions

包含两个注解:@ConditionalOnBean 和 @ConditionalOnMissingBean。

SpringBoot官网的JavaDoc强烈建议开发人员仅在自动装配中使用Bean Conditions条件注解。因为开发人员需要特别小心BeanDefinition的添加顺序,因为这些条件是依赖与迄今为止哪些bean已经被处理来评估的!
在这里插入图片描述

1> @ConditionalOnBean

@ConditionalOnBean注解用于判断某些Bean是否都加载到了Spring容器BeanFactory中,如果是的,则符合条件装配。

使用方式:

@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(ConnectionFactory.class)
public class JmsAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,只有当ConnectionFactory类已经被加载到Spring容器BeanFactory中时,才会加载JmsAutoConfiguration类到Spring容器中。

2> @ConditionalOnMissingBean

@ConditionalOnBean注解用于判断某些Bean是否都没有加载到Spring容器BeanFactory中,如果是的,则符合条件装配。

使用方式:

@Configuration
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public SomeService someService() {
        return new SomeService();
    }

}
AI 代码解读
  • 这里表示,只有当SomeService类没有被加载到Spring容器BeanFactory中时,才会加载SomeService类到Spring容器中。

使用方式2:

@Configuration
public class MyAutoConfiguration {

    @Bean(name = "mySomeService")
    @ConditionalOnMissingBean(name = "mySomeService")
    public SomeService someService() {
        return new SomeService();
    }

}
AI 代码解读
  • 这里同样表示,只有当SomeService类没有被加载到Spring容器BeanFactory中时,才会加载SomeService类到Spring容器中。只是针对类注入到Spring容器时的beanName做了一个自定义。

使用方式3:

@Configuration
public class MyAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(type = "com.fasterxml.jackson.databind.ObjectMapper")    
    public SomeService someService() {
        return new SomeService();
    }

}
AI 代码解读
  • 这里同样表示,只有当Bean类型为com.fasterxml.jackson.databind.ObjectMapper的类没有被加载到Spring容器BeanFactory中时,才会加载SomeService类到Spring容器中。

3)Property Conditions(@ConditionalOnProperty)

@ConditionalOnProperty注解依赖于Spring环境参数(Spring Environment property)来做条件装配。

  1. 其使用prefixname属性表明哪个属性应该被检查。如果prefix()不为空,则属性名称为prefix()+name(),否则属性名称为name()
  2. 默认情况下,匹配存在且不等于false的任何属性。
  3. 此外可以使用havingValuematchIfMissing 属性创建更高级的检查。

    • havingValue() --> 表示期望的配置属性值,并且禁止使用false
    • matchIfMissing() --> 用于判断当属性值不存在时是否匹配

使用方式1:

@Configuration
@ConditionalOnProperty(prefix = "formatter", name = "enabled", havingValue = "true")
public class ForMatterAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,当Spring Environment的属性 formatter.enabled 为“true"时,ForMatterAutoConfiguration才会被加载到Spring容器。

使用方式2:

@Configuration
@ConditionalOnProperty(prefix = "formatter", name = "enabled", havingValue = "true", matchIfMissing = true)
public class ForMatterAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,当属性 formatter.enabled 配置不存在时,同样视作匹配。

4)Resource Conditions(@ConditionalOnResource)

@ConditionalOnResource通过判断某些资源是否存在来做条件装配。

使用方式:

@Configuration
@ConditionalOnResource(resources = {"classpath:META-INF/build-info.properties"})
public class ForMatterAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,只有当classpath:META-INF/build-info.properties文件资源存在时,ForMatterAutoConfiguration才会被加载到Spring容器。

5)Web Application Conditions

包含两个注解:@ConditionalOnWebApplication 和 @ConditionalOnNotWebApplication。

1> @ConditionalOnWebApplication

@ConditionalOnWebApplication用于判断SpringBoot应用的类型是否为指定Web类型(ANY、SERVLET、REACTIVE)。
在这里插入图片描述
使用方式:

@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
public class ForMatterAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,只有当SpringBoot应用类型为SERVLET应用类型时,ForMatterAutoConfiguration才会被加载到Spring容器。

2> @ConditionalOnNotWebApplication

@ConditionalOnNotWebApplication用于判断SpringBoot应用的类型是否为不为Web应用。
在这里插入图片描述
使用方式:

@Configuration
@ConditionalOnNotWebApplication
public class ForMatterAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,只有当SpringBoot应用类型不是Web应用类型时,ForMatterAutoConfiguration才会被加载到Spring容器。

6)SpEL Expression Conditions(ConditionalOnExpression)

@ConditionalOnExpression通过SpEL Expression来做条件装配。

使用这种方式做条件装配有个坑:

  • 其会导致在上下文刷新处理中很早就初始化了被标注的bean,进而导致bean无法进行后置处理(比如配置属性绑定),其状态可能是不完整的。

在这里插入图片描述
所以不建议使用

使用方式:

@Configuration
@ConditionalOnExpression("${formatter.enabled:true} && ${formatter.enabled.dup:true}")
public class ForMatterAutoConfiguration {
    ....
}
AI 代码解读
  • 这里表示,只有当属性formatter.enabledformatter.enabled.dup同时为true时,ForMatterAutoConfiguration才会被加载到Spring容器。

7)其他

除上述官方提供的六类条件装配注解,还有三四个条件装配的注解,其中@ConditionalOnSingleCandidate需要着重看一下

@Conditional扩展注解 作用
@ConditionalOnSingleCandidate 容器中只有一个指定的Bean,或者是首选Bean
@ConditionalOnJava 系统的java版本是否符合要求
@ConditionalOnProperty 系统中指定的属性是否有指定的值
@ConditionalOnJndi JNDI存在指定项
相关文章
保姆级Spring AI 注解式开发教程,你肯定想不到还能这么玩!
这是一份详尽的 Spring AI 注解式开发教程,涵盖从环境配置到高级功能的全流程。Spring AI 是 Spring 框架中的一个模块,支持 NLP、CV 等 AI 任务。通过注解(如自定义 `@AiPrompt`)与 AOP 切面技术,简化了 AI 服务集成,实现业务逻辑与 AI 基础设施解耦。教程包含创建项目、配置文件、流式响应处理、缓存优化及多任务并行执行等内容,助你快速构建高效、可维护的 AI 应用。
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
39 0
Spring Boot的核心注解是哪个?他由哪几个注解组成的?
Spring Boot的核心注解是@SpringBootApplication , 他由几个注解组成 : ● @SpringBootConfiguration: 组合了- @Configuration注解,实现配置文件的功能; ● @EnableAutoConfiguration:打开自动配置的功能,也可以关闭某个自动配置的选项 ● @ComponentScan:Spring组件扫描
Spring MVC常用的注解
@RequestMapping:用于处理请求 url 映射的注解,可用于类或方法上。用于类上,则表示类中 的所有响应请求的方法都是以该地址作为父路径。 @RequestBody:注解实现接收http请求的json数据,将json转换为java对象。 @ResponseBody:注解实现将conreoller方法返回对象转化为json对象响应给客户。 @Controller:控制器的注解,表示是表现层,不能用用别的注解代替 @RestController : 组合注解 @Conntroller + @ResponseBody @GetMapping , @PostMapping , @Put
SpringBoot+@Async注解一起用,速度提升
本文介绍了异步调用在高并发Web应用性能优化中的重要性,对比了同步与异步调用的区别。同步调用按顺序执行,每一步需等待上一步完成;而异步调用无需等待,可提升效率。通过Spring Boot示例,使用@Async注解实现异步任务,并借助Future对象处理异步回调,有效减少程序运行时间。
|
2月前
|
SpringBoot:SpringBoot通过注解监测Controller接口
本文详细介绍了如何通过Spring Boot注解监测Controller接口,包括自定义注解、AOP切面的创建和使用以及具体的示例代码。通过这种方式,可以方便地在Controller方法执行前后添加日志记录、性能监控和异常处理逻辑,而无需修改方法本身的代码。这种方法不仅提高了代码的可维护性,还增强了系统的监控能力。希望本文能帮助您更好地理解和应用Spring Boot中的注解监测技术。
87 16
Spring IOC—基于注解配置和管理Bean 万字详解(通俗易懂)
Spring 第三节 IOC——基于注解配置和管理Bean 万字详解!
216 26
SpringBoot缓存注解使用
Spring Boot 提供了一套方便的缓存注解,用于简化缓存管理。通过 `@Cacheable`、`@CachePut`、`@CacheEvict` 和 `@Caching` 等注解,开发者可以轻松地实现方法级别的缓存操作,从而提升应用的性能和响应速度。合理使用这些注解可以大大减少数据库的访问频率,优化系统性能。
228 89
【SpringFramework】Spring IoC-基于注解的实现
本文主要记录基于Spring注解实现IoC容器和DI相关知识。
80 21
【Spring】方法注解@Bean,配置类扫描路径
@Bean方法注解,如何在同一个类下面定义多个Bean对象,配置扫描路径
221 73
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等