条件装配
@Conditional 此注解是用来判断是否满足指定条件来决定是否进行Bean实例化及装配。
@Conditional 派生条件加载配置注解
- @ConditionalOnBean
- @ConditionalOnMissingBean
- @ConditionalOnClass
- @ConditionalOnMissingClass
- @ConditionalOnProperty
@ConditionalOnBean
当给定的在bean存在时,则实例化当前Bean
@Bean
public People people(City city) {
//这里如果city实体没有成功注入 这里就会报空指针
city.setCityName("千岛湖");
city.setCityCode(301701);
return new People("小小", 3, city);
}
@ConditionalOnBean注解定义
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnBeanCondition.class)
public @interface ConditionalOnBean {
/**
* 需要作为条件的类的Class对象数组
*/
Class<?>[] value() default {};
/**
* 需要作为条件的类的Name,Class.getName()
*/
String[] type() default {};
/**
* (用指定注解修饰的bean)条件所需的注解类
*/
Class<? extends Annotation>[] annotation() default {};
/**
* spring容器中bean的名字
*/
String[] name() default {};
/**
* 搜索容器层级,当前容器,父容器
*/
SearchStrategy search() default SearchStrategy.ALL;
/**
* 可能在其泛型参数中包含指定bean类型的其他类
*/
Class<?>[] parameterizedContainer() default {};
}
@ConditionalOnMissingBean
它作用在@bean定义上,就是在容器加载它作用的bean时, 检查容器中是否存在目标类型(@ConditionalOnMissingBean注解的value值)的bean了, 如果存在这跳过原始bean的默认加载动作 简易:当给定的在bean不存在时,则实例化当前Bean
@ConditionalOnClass
当给定的类名在类路径上存在,则实例化当前Bean
@ConditionalOnMissingClass
当给定的类名在类路径上不存在,则实例化当前Bean
@ConditionalOnProperty
给点对应配置文件的参数符合时,对应的配置才会生效。
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyCondition.class)
public @interface ConditionalOnProperty {
// 数组,获取对应property名称的值,与name不可同时使用
String[] value() default {};
// 配置属性名称的前缀,比如spring.http.encoding
String prefix() default "";
// 数组,配置属性完整名称或部分名称
// 可与prefix组合使用,组成完整的配置属性名称,与value不可同时使用
String[] name() default {};
// 可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置
String havingValue() default "";
// 缺少该配置属性时是否可以加载。如果为true,没有该配置属性时也会正常加载;反之则不会生效
boolean matchIfMissing() default false;
}
装配-先后顺序
@AutoConfigure After | Before | Order
After :在配置类加载之后加载
Before:在配置类加载之前加载 Order:指定在配置类加载顺序
@Configuration
public class co nfigureConfigTest{
}
@Configuration
//在此配置类加载之后 加载configureConfigTest
@AutoConfigureAfter(configureConfigTest.class)
//在此配置类加载之前 加载
@AutoConfigureBefre(configureConfigTest.class)
public class configureConfig{
}