成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

SpringBoot 自動裝配的原理分析

開發 前端
關于 SpringBoot? 的自動裝配功能,相信是每一個 Java 程序員天天都會用到的一個功能,但是它究竟是如何實現的呢?今天阿粉來帶大家看一下。

自動裝配案例

首先我們通過一個案例來看一下自動裝配的效果,創建一個 SpringBoot? 的項目,在 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? 的依賴表示我們這是一個 web? 項目,redis? 的依賴就是我們這邊是要驗證的功能依賴。隨后在 application.properties? 配置文件中增加 redis 的相關配置如下

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

再編寫一個 Controller? 和 Service 類,相關代碼如下。

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") String 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 + " 歡迎關注 Java 極客技術";
}

}

啟動項目,然后我們通過訪問 http://127.0.0.1:8080/hello?name=ziyou,可以看到正常訪問。接下來我們再通過 Redis? 的客戶端,去觀察一下數據是否正確的寫入到 Redis 中,效果跟我們想象的一致。

圖片

自動裝配分析

看到這里很多小伙伴就會說,這個寫法我天天都在使用,用起來是真的爽。雖然用起來是很爽,但是大家有沒有想過一個問題,那就是在我們的 HelloService? 中通過 @Autowired? 注入了一個 RedisTemplate? 類,但是我們的代碼中并沒有寫過這個類,也沒有使用類似于@RestControlle?r,@Service? 這樣的注解將 RedisTemplate? 注入到 Spring IoC? 容器中,那為什么我們就可以通過 @Autowired?  注解從 IoC? 容器中獲取到 RedisTemplate  這個類呢?這里就是常說的自動裝配的功能了。

首先我們看下項目的啟動類;

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);
}
}

在啟動類上面有一個 @SpringBootApplication 注解,我們點進去可以看到如下內容:

@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 {
// 省略
}

在這個注解中,其中有一個 @EnableAutoConfiguration 注解,正是因為有了這樣一個注解,我們才得以實現自動裝配的功能。繼續往下面看。

@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? 注解中有一個 @Import({AutoConfigurationImportSelector.class})?,導入了一個  AutoConfigurationImportSelector? 類,該類間接實現了 ImportSelector? 接口,實現了一個 String[] selectImports(AnnotationMetadata importingClassMetadata);? 方法,這個方法的返回值是一個字符串數組,對應的是一系列主要注入到 Spring IoC? 容器中的類名。當在 @Import? 中導入一個 ImportSelector? 的實現類之后,會把該實現類中返回的 Class? 名稱都裝載到 IoC 容器中。

一旦被裝載到 IoC? 容器中過后,我們在后續就可以通過 @Autowired?  來進行使用了。接下來我們看下 selectImports? 方法里面的實現,當中引用了 getCandidateConfigurations? 方法 ,其中的  ImportCandidates.load? 方法我們可以看到是通過加載 String location = String.format("META-INF/spring/%s.imports", annotation.getName());? 對應路徑下的 org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件,其中就包含了很多自動裝配的配置類。

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;
}

圖片

我們可以看到這個文件中有一個 RedisAutoConfiguration? 配置類,在這個配置中就有我們需要的 RedisTemplate? 類的 Bean?,同時也可以看到,在類上面有一個 @ConditionalOnClass({RedisOperations.class})? 注解,表示只要在類路徑上有 RedisOperations.class 這個類的時候才會進行實例化。這也就是為什么只要我們添加了依賴,就可以自動裝配的原因。

圖片

通過 org.springframework.boot.autoconfigure.AutoConfiguration.imports? 這個文件,我們可以看到有很多官方幫我們實現好了配置類,這些功能只要我們在 pom? 文件中添加對應的 starter 依賴,然后做一些簡單的配置就可以直接使用。

其中本質上自動裝配的原理很簡單,本質上都需要實現一個配置類,只不過這個配置類是官方幫我們創建好了,再加了一些條件類注解,讓對應的實例化只發生類類路徑存在某些類的時候才會觸發。這個配置類跟我們平常自己通過 JavaConfig 形式編寫的配置類沒有本質的區別。

自動裝配總結

從上面的分析我們就可以看的出來,之所以很多時候我們使用 SpringBoot 是如此的簡單,全都是依賴約定優于配置的思想,很多復雜的邏輯,在框架底層都幫我們做了默認的實現。雖然用起來很爽,但是很多時候會讓程序員不懂原理,我們需要做的不僅是會使用,而更要知道底層的邏輯,才能走的更遠。

基于上面的分析,我們還可以知道,如果我們要實現一個自己的 starter? 其實也很簡單,只要安裝上面的約定,編寫我們自己的配置類和配置文件即可。后面的文章阿粉會帶你手寫一個自己的 starter 來具體實現一下。

責任編輯:武曉燕 來源: Java極客技術
相關推薦

2024-05-29 07:47:30

SpringJava@Resource

2023-11-01 09:07:01

Spring裝配源碼

2024-12-25 16:01:01

2023-09-28 09:17:18

SpringBootBean

2025-06-12 05:00:00

@Autowired自動裝配實現機制

2021-06-17 08:05:59

SpringBoot條件裝配

2024-04-26 08:46:42

Spring自動裝配核心內容

2025-05-22 09:54:06

2012-02-17 10:50:10

Java

2011-04-20 09:27:32

Spring

2025-02-05 12:28:44

2012-11-28 10:37:25

Linux集群安裝配置

2022-02-16 09:01:13

iOSS開發XCode

2010-04-29 10:11:07

Linux集群

2023-06-30 07:51:44

springboot初始化邏輯

2016-09-12 14:33:20

javaHashMap

2010-06-29 17:07:10

Linux SNMP代

2024-11-04 16:29:19

2014-08-13 18:47:46

2025-02-27 00:10:19

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 国产精品精品久久久久久 | 日韩成人在线免费观看 | 一区二区三区国产好 | av色站| 国产精品a一区二区三区网址 | av天天干 | 欧美 日韩 综合 | 久久99这里只有精品 | 久久久久久艹 | 玖玖国产精品视频 | 久久久久久久久毛片 | 成人福利在线 | av在线免费观看网站 | 日本一级淫片免费啪啪3 | 在线2区 | 国产亚洲精品久久19p | 日韩一区二区三区在线视频 | 欧美a区| 夜夜摸天天操 | 国产亚洲日本精品 | 黄色精品| 久久青草av | 日韩一区精品 | 欧美一区二区成人 | 成人精品视频99在线观看免费 | 日韩欧美在线免费观看视频 | 欧美多人在线 | 成人在线视频一区二区三区 | 91精品久久久久久久99 | 日韩免费网站 | 欧美一区二区久久 | 国产欧美一级 | 99亚洲 | 久久午夜电影 | 欧美日韩亚洲视频 | 精品视频一区二区三区在线观看 | 四虎永久在线精品免费一区二 | 久久亚洲综合 | 在线观看成人免费视频 | 成人免费一区二区三区牛牛 | 中文字幕亚洲视频 |