SpringBoot 自動(dòng)裝配的原理詳解分析
前言
關(guān)于 ??SpringBoot?
?? 的自動(dòng)裝配功能,相信是每一個(gè) ??Java?
? 程序員天天都會(huì)用到的一個(gè)功能,但是它究竟是如何實(shí)現(xiàn)的呢?今天阿粉來帶大家看一下。
自動(dòng)裝配案例
首先我們通過一個(gè)案例來看一下自動(dòng)裝配的效果,創(chuàng)建一個(gè) ??SpringBoot?
? 的項(xiàng)目,在 ??pom?
? 文件中加入下面的依賴。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
其中 ??web?
? 的依賴表示我們這是一個(gè) ??web?
? 項(xiàng)目,??redis?
? 的依賴就是我們這邊是要驗(yàn)證的功能依賴。隨后在 ??application.properties?
? 配置文件中增加 ??redis?
? 的相關(guān)配置如下
spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=123456
再編寫一個(gè) ??Controller?
? 和 ??Service?
? 類,相關(guān)代碼如下。
package com.example.demo.controller; import com.example.demo.service.HelloService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired private HelloService helloService; @GetMapping(value = "/hello") public String hello(@RequestParam("name"){ return helloService.sayHello(name); } }
??service?? 代碼如下:
package com.example.demo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @Service public class HelloService { @Autowired RedisTemplate<String, String> redisTemplate; public String sayHello(String name){ String result = doSomething(name); redisTemplate.opsForValue().set("name", result); result = redisTemplate.opsForValue().get("name"); return "hello: " + result; } private String doSomething(String name){ return name + " 歡迎關(guān)注 Java 極客技術(shù)"; } }
啟動(dòng)項(xiàng)目,然后我們通過訪問 http://127.0.0.1:8080/hello?name=ziyou,可以看到正常訪問。接下來我們?cè)偻ㄟ^ ??Redis?
? 的客戶端,去觀察一下數(shù)據(jù)是否正確的寫入到 ??Redis?
? 中,效果跟我們想象的一致。
自動(dòng)裝配分析
看到這里很多小伙伴就會(huì)說,這個(gè)寫法我天天都在使用,用起來是真的爽。雖然用起來是很爽,但是大家有沒有想過一個(gè)問題,那就是在我們的 ??HelloService?
? 中通過 ??@Autowired?
? 注入了一個(gè) ??RedisTemplate?
? 類,但是我們的代碼中并沒有寫過這個(gè)類,也沒有使用類似于??@RestControlle?
?r,??@Service?
? 這樣的注解將 ??RedisTemplate?
? 注入到 ??Spring IoC?
? 容器中,那為什么我們就可以通過 ??@Autowired?
? 注解從 ??IoC?
? 容器中獲取到 ??RedisTemplate?
?
首先我們看下項(xiàng)目的啟動(dòng)類:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan(value = "com.example.demo.*") public class DemoApplication { public static void main(String[] args){ SpringApplication.run(DemoApplication.class, args); } }
在啟動(dòng)類上面有一個(gè) ??@SpringBootApplication?
? 注解,我們點(diǎn)進(jìn)去可以看到如下內(nèi)容:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} ) public @interface SpringBootApplication { // 省略 }
在這個(gè)注解中,其中有一個(gè) ??@EnableAutoConfiguration?
? 注解,正是因?yàn)橛辛诉@樣一個(gè)注解,我們才得以實(shí)現(xiàn)自動(dòng)裝配的功能。繼續(xù)往下面看。
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import({AutoConfigurationImportSelector.class}) public @interface EnableAutoConfiguration { String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration"; Class<?>[] exclude() default {}; String[] excludeName() default {}; }
可以看到 ??@EnableAutoConfiguration?? 注解中有一個(gè) ??@Import({AutoConfigurationImportSelector.class})??,導(dǎo)入了一個(gè) ??AutoConfigurationImportSelector?? 類,該類間接實(shí)現(xiàn)了 ??ImportSelector?? 接口,實(shí)現(xiàn)了一個(gè) ??String[] selectImports(AnnotationMetadata importingClassMetadata);?? 方法,這個(gè)方法的返回值是一個(gè)字符串?dāng)?shù)組,對(duì)應(yīng)的是一系列主要注入到 ??Spring IoC?
? 容器中的類名。當(dāng)在 ??@Import?
? 中導(dǎo)入一個(gè) ??ImportSelector?
? 的實(shí)現(xiàn)類之后,會(huì)把該實(shí)現(xiàn)類中返回的 ??Class?
? 名稱都裝載到 ??IoC?
? 容器中。
一旦被裝載到 ??IoC?
? 容器中過后,我們?cè)诤罄m(xù)就可以通過 ??@Autowired?
? 來進(jìn)行使用了。接下來我們看下 ??selectImports?
? 方法里面的實(shí)現(xiàn),當(dāng)中引用了 ??getCandidateConfigurations?
? 方法 ,其中的 ??ImportCandidates.load?? 方法我們可以看到是通過加載 ??String location = String.format("META-INF/spring/%s.imports", annotation.getName());?? 對(duì)應(yīng)路徑下的 ??org.springframework.boot.autoconfigure.AutoConfiguration.imports?? 文件,其中就包含了很多自動(dòng)裝配的配置類。
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes){ List<String> configurations = new ArrayList(SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader())); ImportCandidates.load(AutoConfiguration.class, this.getBeanClassLoader()).forEach(configurations::add); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories nor in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. If you are using a custom packaging, make sure that file is correct."); return configurations; }
我們可以看到這個(gè)文件中有一個(gè) ??RedisAutoConfiguration?
? 配置類,在這個(gè)配置中就有我們需要的 ??RedisTemplate?
? 類的 ??Bean?
?,同時(shí)也可以看到,在類上面有一個(gè) ??@ConditionalOnClass({RedisOperations.class})?
? 注解,表示只要在類路徑上有 ??RedisOperations.class ?
?這個(gè)類的時(shí)候才會(huì)進(jìn)行實(shí)例化。這也就是為什么只要我們添加了依賴,就可以自動(dòng)裝配的原因。
通過 ??org.springframework.boot.autoconfigure.AutoConfiguration.imports?
? 這個(gè)文件,我們可以看到有很多官方幫我們實(shí)現(xiàn)好了配置類,這些功能只要我們?cè)?nbsp;??pom?
? 文件中添加對(duì)應(yīng)的 ??starter?
? 依賴,然后做一些簡(jiǎn)單的配置就可以直接使用。
其中本質(zhì)上自動(dòng)裝配的原理很簡(jiǎn)單,本質(zhì)上都需要實(shí)現(xiàn)一個(gè)配置類,只不過這個(gè)配置類是官方幫我們創(chuàng)建好了,再加了一些條件類注解,讓對(duì)應(yīng)的實(shí)例化只發(fā)生類類路徑存在某些類的時(shí)候才會(huì)觸發(fā)。這個(gè)配置類跟我們平常自己通過 ??JavaConfig?
? 形式編寫的配置類沒有本質(zhì)的區(qū)別。
自動(dòng)裝配總結(jié)
從上面的分析我們就可以看的出來,之所以很多時(shí)候我們使用 ??SpringBoot?
? 是如此的簡(jiǎn)單,全都是依賴約定優(yōu)于配置的思想,很多復(fù)雜的邏輯,在框架底層都幫我們做了默認(rèn)的實(shí)現(xiàn)。雖然用起來很爽,但是很多時(shí)候會(huì)讓程序員不懂原理,我們需要做的不僅是會(huì)使用,而更要知道底層的邏輯,才能走的更遠(yuǎn)。
基于上面的分析,我們還可以知道,如果我們要實(shí)現(xiàn)一個(gè)自己的 ??starter?
? 其實(shí)也很簡(jiǎn)單,只要安裝上面的約定,編寫我們自己的配置類和配置文件即可。后面的文章阿粉會(huì)帶你手寫一個(gè)自己的 ??starter?
? 來具體實(shí)現(xiàn)一下。
到此這篇關(guān)于SpringBoot 自動(dòng)裝配的原理詳解分析的文章就介紹到這了,更多相關(guān)SpringBoot 自動(dòng)裝配 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Springboot+React項(xiàng)目跨域訪問問題
這篇文章主要介紹了詳解Springboot+React項(xiàng)目跨域訪問問題,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-11-11spring實(shí)現(xiàn)bean對(duì)象創(chuàng)建代碼詳解
這篇文章主要介紹了spring實(shí)現(xiàn)bean對(duì)象創(chuàng)建代碼詳解,具有一定借鑒價(jià)值,需要的朋友可以參考下2017-12-12Java 數(shù)組元素倒序的三種方式(小結(jié))
這篇文章主要介紹了Java 數(shù)組元素倒序的三種方式(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09Spring Cloud下基于OAUTH2認(rèn)證授權(quán)的實(shí)現(xiàn)示例
這篇文章主要介紹了Spring Cloud下基于OAUTH2認(rèn)證授權(quán)的實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03spring中@Configuration和@Bean注解的用法
這篇文章主要介紹了spring中@Configuration和@Bean注解的用法,@Configuration用于定義配置類,可替換xml配置文件,被注解的類內(nèi)部包含有一個(gè)或多個(gè)被@Bean注解的方法,需要的朋友可以參考下2023-05-05IntelliJ IDEA 如何徹底刪除項(xiàng)目的步驟
本篇文章主要介紹了IntelliJ IDEA 如何徹底刪除項(xiàng)目的步驟,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-11-11