SpringBoot自動裝配,比較全的吧,來看看吧~


文章挺長,表達不好,希望能有獲~~~~

Spring也提供使用注解來注冊bean,為什么要用SpringBoot呢?

使用Spring應用,比如SpringMVC還行需要配置ViewResolver、DispatcherServlet,使用Mybatis等也需要進行其他配置。

如下為spring-mybatis配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
	<!-- 導入屬性配置文件 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
 
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
	</bean>
	<!-- 將數據源映射到sqlSessionFactory中 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
		<property name="dataSource" ref="dataSource" />
		<!--<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" />-->
	</bean>
 
	<!-- SqlSession模板類實例 -->
	<bean id="sessionTemplate" class="org.mybatis.spring.SqlSessionTemplate" destroy-method="close">
		<constructor-arg index="0" ref="sqlSessionFactory" />
	</bean>
 
	<!--======= 事務配置 Begin ================= -->
	<!-- 事務管理器(由Spring管理MyBatis的事務) -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 關聯數據源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!--======= 事務配置 End =================== -->
	
	<!--mapper配置-->
	<bean id="kbCityMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
		<property name="mapperInterface" value="com.spring.dao.KbCityMapper" />
		<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	</bean>
</beans>

SpringBoot進行自動配置不在需用使用者進行這些配置。而且使用SpringBoot也不需要管理Mybatis、log4j、jackson等依賴包的版本問題,SpringBoot使用starter進行依賴管理。

使用SpringBoot只需在application.ymlapplication.xml添加少量配置,通過@SpringBootApplication即可啟動應用。

我們從spring文檔看一看

自動裝配的意義在於SpringBoot提前為我們初始化了一些東西,從SpringBoot文檔中搜索Auto-configuration

對於JSON mapping libraries:

image-20210425201411731

對於Spring MVC:

image-20210425201444384

可以看到有對BeanNameViewResolver的自動配置。

對於模板引擎:

image-20210425201709479

可以看到對Thymeleaf的自動配置,我們只需要引入Thymeleaf依賴就能直接用了,不需要任何配置。

對Reids:

image-20210425202428406

還有對Security,Spring Data JPA,Elasticsearch等等很多很多,SpringBoot都對他們提前進行了一些配置,這樣使得我們只需引入其依賴,只需要在application.yml少量配置甚至不需要配置就可以直接使用。


我們從jar包的源碼看一看

image-20210425205723641

文檔說讓我們瀏覽spring-boot-autoconfigure的源代碼,那么我們就看看源碼:

image-20210425205939115

先說一下META-INF包下的,我們看一看additional-spring-configuration-metadata.json這個文件里有啥呢?

我們看一看其中server.port:

image-20210425210933833

嗯,他默認值是8080,是不是很熟悉呢?我們進入我們項目的application.properties

image-20210425211045190

image-20210425211121166

那么我們再看看server.servlet.encoding.enabledserver.servlet.jsp.class-name這兩個

image-20210425211338516

image-20210425211418156

這回我們知道原來application.properties中的默認值是從additional-spring-configuration-metadata.json這個文件來的呀。

接下來看看spring.factories文件:

image-20210425212431574

里面都是一些AutoConfiguration類的完整類路徑,那么我們有了類路徑能干啥呢?那當然通過反射創建該類了。那么有這么多自動配置類肯定不會全部加載,那些我們要用到SpringBoot就加載哪些。

spring-autoconfigure-metadata.properties:看其內容,等號左邊為類路徑或屬性,右邊或者類路徑或者值或者空。應該跟我們平常的properties文件一樣的意思吧,為了不將這些配置屬性在代碼中寫死,將其提取出來放到properties文件中。

spring-autoconfigure-metadata.json:只知道name與sourceType,type,sourceMethod建立映射關系,不知道干啥用。或許為了通過name標識值在代碼中更清晰易懂吧。

繼續向下看:

image-20210425220234468

這里面可以看到很多熟悉的名字,我們以web包為例看一看吧:

image-20210425220439111

這些類大致分為兩種,一種AutoConfiguration,一種Properties

題外話:我們知道SpringBoot掃描靜態資源時會在/resources/, /static/, /public/這些路徑下。我們看看WebProperties.java

image-20210425221258845

接着我們以WebMvcPropertiesWebMvcAutoConfiguration為例看一看吧。

WebMvcProperties:就在這個屬性類中完成了webMvc相關屬性的初始化工作。

某些屬性如下:

	private String staticPathPattern = "/**";

	public static class Servlet {

		/**
		 * Path of the dispatcher servlet. Setting a custom value for this property is not
		 * compatible with the PathPatternParser matching strategy.
		 */
		private String path = "/";
    
		public String getServletMapping() {
			if (this.path.equals("") || this.path.equals("/")) {
				return "/";
			}
			if (this.path.endsWith("/")) {
				return this.path + "*";
			}
			return this.path + "/*";
		}
	}

WebMvcAutoConfiguration:這個類就通過get方法,從上面的properties文件中取值,有了這些屬性值,那么就能完成webMvc相關類的初始化工作了!!!

接下來從springbootApplication注解,進入來看看吧

image-20210426204624517

@SpringBootConfiguration:進去看后是一個@Configuration,因此SpringBootConfiguration注解的作用是將其注解的類注冊到spring中。

@ComponentScan:組件掃描類,在此包下的被controller,service,component等注解類注冊到spring中。

@EnableAutoConfiguration:以下主要分析。

image-20210426205040918

查看@AutoConfigurationPackage

image-20210426205147178

進入AutoConfigurationPackages.Registrar.class

image-20210426205320143

debug一下registerBeanDefinitions方法:login

通過上面的gif我們可以看到registerBeanDefinitions這個方法應該就是注冊我們自己包下所有bean。

接着進入AutoConfigurationImportSelector.class

進入getAutoConfigurationEntry->getCandidateConfigurations->loadFactoryNames->loadSpringFactories

image-20210426215456442

這里會獲取到spring.factories文件,然后加載他,然后循環遍歷將其放入result中。

image-20210426215716660

我們debug進入時:

image-20210426221005559

result為一個map,我們以org.springframework.boot.autoconfigure.EnableAutoConfiguration為key,取出那size為130的List<String>

image-20210426221252130

現在我們從getCandidateConfigurations出來了,configuration的size大小130,然后去重,排除。

image-20210426221723546

在執行getConfigurationClassFilter().filter(configurations);方法前configurations的size還為130。

執行之后:

image-20210426221756839

最終我們加載了這23個配置類。

image-20210426222136717

如何創建自己的starter?

image-20210426222710238

demo project我看了,六年前更新的,使用的springboot1,很老的版本了。這個示例的pom的依賴引入的很繁雜,可以看看人家寫的自動配置類,挺齊全的。

image-20210426225436189

三個點:

  • pom文件引入springboot依賴(我看guide哥的博客,直接引入這個依賴就能用了。)
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.4.5</version>
      <scope>compile</scope>
</dependency>
  • 創建自動配置類,其上有必須@Configuration,其他約束性注解根據情況添加
  • 將這個自動配置類寫到,spring.factories文件

終於完結。

😄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM