Spring boot 自动装配原理

上一篇Spring boot 回顾。这一篇我们看一下Spring boot 自动装配的原理。

1. 简单的 Bean 装配

@Data
public class Student {
    private String name;
    private int age;
}

@Configuration
public class SingleConfiguration {

    @Bean
   public Student student(){
    Student student=new Student();
    student.setName("zhangsan");
    student.setAge(30);
   return student;
}

// 验证
AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(SingleConfiguration.class);
Student student= (Student) context.getBean("student");

2. 匹配 Bean 装配

通过 @ComponentScan 注解扫描包路径,实现匹配 Bean 扫描装配

@Configuration
@ComponentScan("com.xx.xx")
public class BatchConfiguration {

}

3. Spring boot 各种 starter 怎么装配

约定优于配置

starter 需要做
1 )创建 META-INF/spring.factories 文件
2 )通过指定的 key ,把配置类的信息进行配置,比如:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.xx.Mybati
sAutoConfiguration
3 )看看其他 starter ,比如: mybatis nacos
对于 Spring Boot 项目而言,目的就是寻找所有 starter 中指定配置文件中的配置类:
1 @SpringBootApplication->@EnableAutoConfiguration-
>@Import(AutoConfigurationImportSelect.class)
2 AutoConfigurationImportSelect#getAutoConfigurationEntry-
>getCandidateConfigurations

条件装配:

满足特定的条件,Bean 才会被注入到 Ioc 容器中。

大家可能有发现过这种现象,项目依赖了 xxx-starter,而且 xxx-starter 里自身使用的某些依赖我们没有引入。但是项目可以正常启动。为啥呢?原因是 xxx-starter 没有满足条件,没有装配。

条件装配有以下注解:

1 ConditionalOnClass :当且仅当 ClassPath 存在指定的 Class 时,才创建标记上该注解的类的实例
2 ConditionalOnBean: 当且仅当指定的 bean classes and/or bean names 在当前容器中 , 才创建
标记上该注解的类的实例
3 ConditionalOnProperty :当且仅当 Application.properties 存在指定的配置项时,创建标记上
了该注解的类的实例
4 ConditionalOnResource :在 classpath 下存在指定的 resource 时创建
5 ConditionalOnWebApplication :在 web 环境下创建
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值