@Conditional注解
dicates that a component is only eligible for registration when all specified conditions match”,意思是只有满足一些列条件之后创建一个bean。
@Conditional定义
@Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD}) public @interface Conditional { Class<? extends Condition>[] value(); }
通过实现Condition接口,并重写其matches方法来构造判断条件。
Windows的条件
public class WindowsCondition implements Condition{ @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){ return context.getEnvironment().getProperty("os.name").contains("Windows"); } }
配置类
@Configuration public class ConditionConfig { //matches方法返回true的,就运行哪个方法 @Bean @Conditional(WindowsCondition.class)//通过@Condition注解,符合Windows条件则实例化windowsListService public ListService windowsListService(){ return new WindowsListService(); } }
@Conditional 注解接收的参数是 extends Condition 接口的泛型类,也就是说,要使用 @Conditional 注解,只需要实现 Condition 接口并重写其方法即可:
package com.springframe.context.annotation; public interface Condition{ boolean matches(ConditionContext context,AnnotatedTypeMetadata metadata); }
@Conditional注解主要用在以下位置:
- 类级别可以放在注标识有@Component(包含@Configuration)的类上
- 作为一个meta-annotation,组成自定义注解
- 方法级别可以放在标识由@Bean的方法上
- ConditionalOnBean: 当且仅当指定的bean classes and/or bean names在当前容器中,才创建标记上该注解的类的实例
- ConditionalOnMissingBean: 当且仅当指定的bean classes and/or bean names不存在当前容器中,才创建标记上该注解的类的实例,有指定忽略ignored的参数存在,可以忽略Class、Type等
- ConditionalOnClass:当且仅当ClassPath存在指定的Class时,才创建标记上该注解的类的实例
- ConditionalOnMissingClass:当且仅当ClassPath不存在指定的Class时,创建标记上该注解的类的实例
- ConditionalOnProperty:当且仅当Application.properties存在指定的配置项时,创建标记上了该注解的类的实例
@Configuration @ConditionalOnProperty(value="mybean.enabled",havingValue="true”,matchIfMissing=true) public class MyBean{ }
application.properties 或 application.yml 文件中 mybean.enable 为 true 才会加载 MyCondition 这个 Bean,如果没有匹配上也会加载,因为 matchIfMissing = true,默认值是 false。
- ConditionalOnJava:指定JDK的版本
- ConditionalOnExpression:表达式用${..}=false等来表示
@Configuration @ConditionalOnExpression("${mybean.enabled:true} and ${otherbean.enabled:true}") public class MyBean{ }
只有当两个属性都为 true 的时候才加载 MyModule
- ConditionalOnJndi:JNDI存在该项时创建
- ConditionalOnResource:在classpath下存在指定的resource时创建
- ConditionalOnSingleCandidate:Conditional
that only matches when the specified bean class is already contained in the BeanFactory
and a single candidate can be determined.The condition will also match if multiple matching bean instances are already contained in the BeanFactory
but a primary candidate has been defined; essentially, the condition match if auto-wiring a bean with the defined type will succeed. - ConditionalOnWebApplication:只有运行在 web 应用里才会加载这个 bean
@Configuration @ConditioanalOnWebApplication class OnWebApplicationModule{ }
组合条件 AND: 继承 AllNestedConditions类封装我们多个条件
组合条件 OR: 通过继承 AnyNestedCondition
立志如山 静心求实
浙公网安备 33010602011771号