自动装配
2022-04-07 17:35:00 4 举报
自动装配总结
作者其他创作
大纲/内容
AutoConfigurationImportSelector实现,返回实现类Class名称的数组,并将其装配到ioc容器
@AutoConfigurationPackage使用该注解的类所在的包及其子包下所有组件扫描到spring Ioc 容器中
public class User{ private Long id; private String name;省略getter、setter、构造函数}
实现例子
public interface ImportSelector { String[] selectImports(AnnotationMetadata var1);} 数组中可以指定需要装配到IOC容器的类 可以批量装配 通过逻辑处理来实现Bean的选择性装配(根据上下文决定那些类能够被IOC容器初始化)
扩展@Conditional条件装配
条件接口返回true注入,false不注入
font color=\"#e65100\
public class DogConditional implements Condition { @Overridefont color=\"#f57f17\
全局bean注入
@ConditionalOnProperty@Configuration@ConditionalOnProperty(value=\"gp.bean0enable\
自动装配
public class UserConditional implements Condition { @Overridefont color=\"#f57f17\
自动装配流程1.通过@Import(AutoConfigurationImportSelector)实现配置类导入,但是这里不是传统span style=\
@EnableAutoConfiguration
包含
user的条件装配-配置
dog的条件装配-配置
其中en.conf为全局配置用于区分注册什么类型的bean
@Configurationpublic class DemoConfig { @Conditional(UserConditional.class) @Bean(name = \"user\") public User user(){ User user = new User(); user.setId(1L); user.setName(\"男用户\"); return user; } @Conditional(DogConditional.class) @Bean(name = \"dog\") public Dog dog(){ Dog dog = new Dog(); dog.setId(2L); dog.setName(\"小白\"); return dog; }}
public class Dog { private Long id; private String name;省略getter、setter、构造函数}
@Import(AutoConfigurationImportSelector.class)导入的不是一个Configuration类是一个AutoConfigurationImportSelector类
测试例子
注入的UserBean
@SpringBootApplicationpublic class ConditionalApplication10000 { public static void main(String[] args) { System.setProperty(\"en.conf\
当Spring Ioc容器中存在GpBean时,才会加载ConditionConfig
在application.properties或application.yml中,当gp.bean.enable=true时才会加载ConditionConfig这个bean,如果没匹配上也会加载因为matchIfMissing=true,默认false
@FunctionalInterfacepublic interface Condition {font color=\"#e65100\
实现方法
@ConditionalOnResource@Configuration@ConditionalOnResource(resource=\"gp.properties\")public class ConditionConfig{}
@SpringBootApplication
注解类
启动类
注入的DogBean
@Overridepublic String[] selectImports(AnnotationMetadata annotationMetadata) { if (!isEnabled(annotationMetadata)) { return NO_IMPORTS; } AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);font color=\"#e65100\
@Configuration@ConditionalOnBean(GpBean.class)public class ConditionConfig{}
======= 注册 bean =======public class FirstClass { private String name = \"FirstClass\"; 构造、setter、getter、tostring省略}public class SecondClass { private String name = \"SecondClass\"; 构造、setter、getter、tostring省略}=======ImportSelector实现类==public class GpImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata annotationMetadata) {font color=\"#f57f17\
0 条评论
下一页