Springboot自动装配

什么是自动装配

假设我们要引入redis

<dependency>
   <groupId> org.springframework.boot </groupId>
   <artifactId> spring-boot-starter-data-redis </artifactId>
</dependency>

然后在application.properties配置Redis数据源

spring.redis.host=localhost
spring.redis.port=6379

当我们需要操作redis时只需要

@Autowired
RedisTemplate<String,String> redisTemplate

这个RedisTemplate实例时何时注入容器的? 这就是自动装配

原理

我们从启动类注解开始

这里由@EnableAutoConfiguration完成自动装配

我们追进去看看

比较重要的是
@AutoConfigurationPackage (它的作用是把使用该注解的类所在的包及子包下所有组件注册到spring容器中)
@Import({EnableAutoConfigurationImportSelector.class})

@Import加载了一个类,我们进去看看

看样子方法实现都在父类中,我们去父类看看

主要是由selectImports方法完成自动装配!他会把需要自动装配的类名返回!

getCandidateConfigurations方法获得需要自动装配的类,我们进去看看

这里用到了SpringFactoriesLoader.loadFactoryNames

可以看到它主要去扫描所有具有META-INF/spring.factories的jar包,,该文件以键=值的形式组成的,并解析获得EnableAutoConfiguration对应的值作为类名列表

举个🌰

这些类会有成员变量,成员变量对应着properties或者yml文件的字段

以上分析来自springboot 1.5版本,但2.0+版本应该总体原理也差不多

posted @ 2021-10-03 17:32  刚刚好。  阅读(278)  评论(0编辑  收藏  举报