日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot基础篇

發布時間:2025/7/14 javascript 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot基础篇 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

配置maven

file-setting-build-build tool

將項目配置成可執行jar

1打包

mavenProject-lifecircle-package

2尋找

target

3執行

cd 包在的目錄- java -jar

Spring Inititer

resource的目錄結構:static:靜態資源? ? templates:模板頁面? application.properties:應用全局配置文件

yaml

yml:yaml a(isn't) makeup language :一個標記語言

優勢:以數據為中心

書寫格式:

k: v:字面直接來寫;
字符串默認不用加上單引號或者雙引號;
"":雙引號;不會轉義字符串里面的特殊字符;特殊字符會作為本身想表示的意思
name: "zhangsan \n lisi":輸出;zhangsan 換行 lisi
'':單引號;會轉義特殊字符,特殊字符最終只是一個普通的字符串數據
name: ‘zhangsan \n lisi’:輸出;zhangsan \n lisi

對象還是k: v的方式

friends:
  lastName: zhangsan
  age: 20

行內寫法:

friends: {lastName: zhangsan,age: 18}

數組(List、Set):

用- 值表示數組中的一個元素

pets:
- cat
- dog
- pig

行內寫法

pets: [cat,dog,pig]

配置文件值注入到具體的實體類里

配置文件

person:
  lastName: hello
  age: 18
  boss: false
  birth: 2017/12/12
  maps: {k1: v1,k2: 12}
  lists:
    - lisi
    - zhaoliu
dog:
  name: 小狗
  age: 12

javaBean:?將配置文件中配置的每一個屬性的值,映射到這個組件中

@Component//只有這個組件是容器中的組件,才能容器提供的@ConfigurationProperties功能;
@ConfigurationProperties(prefix = "person")//告訴SpringBoot將本類中的所有屬性和配置文件中相關的配置進行綁定;

* prefix = "person":配置文件中哪個下面的所有屬性進行一一映射

@Validated//配置文件注入值數據校驗

public class Person {

//lastName必須是郵箱格式
@Email
private String lastName;
private Integer age;
private Boolean boss;

private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;

}

<!--導入配置文件處理器,配置文件進行綁定就會有提示-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>

?@PropertySource(value = {"classpath:person.properties"})載指定的配置文件;

多Profile文件

我們在主配置文件編寫的時候,文件名可以是 application-{profile}.properties/yml

默認使用application.properties的配置;

yml支持多文檔塊方式

server:
  port: 8081
  spring:
  profiles:
  active: prod

---
server:
  port: 8083
  spring:
  profiles: dev

---

server:
  port: 8084
  spring:
  profiles: prod #指定屬于哪個環境

激活指定profile:在配置文件中指定 spring.profiles.active=dev

springboot 啟動會掃描以下位置的application.properties或者application.yml文件作為Spring boot的默認配置文件

–file:./config/

–file:./

–classpath:/config/

–classpath:/

優先級由高到底,高優先級的配置會覆蓋低優先級的配置;

SpringBoot會從這四個位置全部加載主配置文件

@ImportResource:導入Spring的配置文件,讓配置文件里面的內容生效;

spring中添加一個對象

Spring Boot里面沒有Spring的配置文件,我們自己編寫的配置文件,也不能自動識別;

想讓Spring的配置文件生效,加載進來;

@ImportResource標注在一個配置類上

@ImportResource(locations = {"classpath:beans.xml"})
導入Spring的配置文件讓其生效

不來編寫Spring的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
? ? ? xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
? ? ? xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
?
?
? ?<bean id="helloService" class="com.atguigu.springboot.service.HelloService"></bean>
</beans>

SpringBoot推薦給容器中添加組件的方式;推薦使用全注解的方式

1、配置類@Configuration------>Spring配置文件

2、使用@Bean給容器中添加組件

/**
* @Configuration:指明當前類是一個配置類;就是來替代之前的Spring配置文件
*
* 在配置文件中用<bean><bean/>標簽添加組件
*
*/
@Configuration
public class MyAppConfig {
?
? ?//將方法的返回值添加到容器中;容器中這個組件默認的id就是方法名
? ?@Bean
? ?public HelloService helloService02(){
? ? ? ?System.out.println("配置類@Bean給容器中添加組件了...");
? ? ? ?return new HelloService();
? }
}

自動配置的原理

1、自動配置原理:

1)、SpringBoot啟動的時候加載主配置類,開啟了自動配置功能 ==@EnableAutoConfiguration==

2)、@EnableAutoConfiguration 作用:

  • 利用EnableAutoConfigurationImportSelector給容器中導入一些組件?

  • 可以查看selectImports()方法的內容;

  • List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);獲取候選的配置

    • SpringFactoriesLoader.loadFactoryNames()
      掃描所有jar包類路徑下 ?META-INF/spring.factories
      把掃描到的這些文件的內容包裝成properties對象
      從properties中獲取到EnableAutoConfiguration.class類(類名)對應的值,然后把他們添加在容器中

==將 類路徑下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;==

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
........

每一個這樣的 xxxAutoConfiguration類都是容器中的一個組件,都加入到容器中;用他們來做自動配置;

3)、每一個自動配置類進行自動配置功能;

4)、以HttpEncodingAutoConfiguration(Http編碼自動配置)為例解釋自動配置原理;

@Configuration ? //表示這是一個配置類,以前編寫的配置文件一樣,也可以給容器中添加組件
@EnableConfigurationProperties(HttpEncodingProperties.class) ?//啟動指定類的ConfigurationProperties功能;將配置文件中對應的值和HttpEncodingProperties綁定起來;并把HttpEncodingProperties加入到ioc容器中
@ConditionalOnWebApplication //Spring底層@Conditional注解(Spring注解版),根據不同的條件,如果滿足指定的條件,整個配置類里面的配置就會生效; ? 判斷當前應用是否是web應用,如果是,當前配置類生效
@ConditionalOnClass(CharacterEncodingFilter.class) ?//判斷當前項目有沒有這個類CharacterEncodingFilter;SpringMVC中進行亂碼解決的過濾器;
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) ?//判斷配置文件中是否存在某個配置 spring.http.encoding.enabled;如果不存在,判斷也是成立的
//即使我們配置文件中不配置pring.http.encoding.enabled=true,也是默認生效的;
public class HttpEncodingAutoConfiguration {
//他已經和SpringBoot的配置文件映射了
private final HttpEncodingProperties properties;
? //只有一個有參構造器的情況下,參數的值就會從容器中拿
public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
this.properties = properties;
}
? ?@Bean ? //給容器中添加一個組件,這個組件的某些值需要從properties中獲取
@ConditionalOnMissingBean(CharacterEncodingFilter.class) //判斷容器沒有這個組件?
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
return filter;
}

根據當前不同的條件判斷,決定這個配置類是否生效?

一但這個配置類生效;這個配置類就會給容器中添加各種組件;這些組件的屬性是從對應的properties類中獲取的,這些類里面的每一個屬性又是和配置文件綁定的;

5)、所有在配置文件中能配置的屬性都是在xxxxProperties類中封裝者;配置文件能配置什么就可以參照某個功能對應的這個屬性類


@ConfigurationProperties(prefix = "spring.http.encoding") ?//從配置文件中獲取指定的值和bean的屬性進行綁定
public class HttpEncodingProperties {
?
? public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

精髓:

? 1)、SpringBoot啟動會加載大量的自動配置類

? 2)、我們看我們需要的功能有沒有SpringBoot默認寫好的自動配置類;

? 3)、我們再來看這個自動配置類中到底配置了哪些組件;(只要我們要用的組件有,我們就不需要再來配置了)

? 4)、給容器中自動配置類添加組件的時候,會從properties類中獲取某些屬性。我們就可以在配置文件中指定這些屬性的值。

?

xxxxAutoConfigurartion:自動配置類;

給容器中添加組件

xxxxProperties:封裝配置文件中相關屬性;

?

2、細節

?

1、@Conditional派生注解(Spring注解版原生的@Conditional作用)

作用:必須是@Conditional指定的條件成立,才給容器中添加組件,配置配里面的所有內容才生效;

@Conditional擴展注解作用(判斷是否滿足當前指定條件)
@ConditionalOnJava系統的java版本是否符合要求
@ConditionalOnBean容器中存在指定Bean;
@ConditionalOnMissingBean容器中不存在指定Bean;
@ConditionalOnExpression滿足SpEL表達式指定
@ConditionalOnClass系統中有指定的類
@ConditionalOnMissingClass系統中沒有指定的類
@ConditionalOnSingleCandidate容器中只有一個指定的Bean,或者這個Bean是首選Bean
@ConditionalOnProperty系統中指定的屬性是否有指定的值
@ConditionalOnResource類路徑下是否存在指定資源文件
@ConditionalOnWebApplication當前是web環境
@ConditionalOnNotWebApplication當前不是web環境
@ConditionalOnJndiJNDI存在指定項

自動配置類必須在一定的條件下才能生效;

我們怎么知道哪些自動配置類生效;

==我們可以通過啟用 debug=true屬性;來讓控制臺打印自動配置報告==,這樣我們就可以很方便的知道哪些自動配置類生效;

日志

springBoot日志類似于JDBC---數據庫驅動原理:

? 寫了一個統一的接口層;日志門面(日志的一個抽象層);logging-abstract.jar;

? 給項目中導入具體的日志實現就行了;我們之前的日志框架都是實現的抽象層;

?

市面上的日志框架;

JUL、JCL、Jboss-logging、logback、log4j、log4j2、slf4j....

日志門面 (日志的抽象層)日志實現
JCL(Jakarta Commons Logging) SLF4j(Simple Logging Facade for Java) jboss-loggingLog4j JUL(java.util.logging) Log4j2 Logback

左邊選一個門面(抽象層)、右邊來選一個實現;

日志門面: SLF4J;

日志實現:Logback;?

SpringBoot:底層是Spring框架,Spring框架默認是用JCL;‘

? ==SpringBoot選用 SLF4j和logback;==

2、SLF4j使用

1、如何在系統中使用SLF4j https://www.slf4j.org

以后開發的時候,日志記錄方法的調用,不應該來直接調用日志的實現類,而是調用日志抽象層里面的方法;

給系統里面導入slf4j的jar和 logback的實現jar

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
?public static void main(String[] args) {
? ?Logger logger = LoggerFactory.getLogger(HelloWorld.class);
? ?logger.info("Hello World");
}
}

圖示;

每一個日志的實現框架都有自己的配置文件。使用slf4j以后,配置文件還是做成日志實現框架自己本身的配置文件;

2、遺留問題

a(slf4j+logback): Spring(commons-logging)、Hibernate(jboss-logging)、MyBatis、xxxx

統一日志記錄,即使是別的框架和我一起統一使用slf4j進行輸出?

如何讓系統中所有的日志都統一到slf4j;

==1、將系統中其他日志框架先排除出去;==

==2、用中間包來替換原有的日志框架;==

==3、我們導入slf4j其他的實現==

?

3、SpringBoot日志關系


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

?

SpringBoot使用它來做日志功能;


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

底層依賴關系

總結:

? 1)、SpringBoot底層也是使用slf4j+logback的方式進行日志記錄

? 2)、SpringBoot也把其他的日志都替換成了slf4j;

? 3)、中間替換包?

@SuppressWarnings("rawtypes")
public abstract class LogFactory {
?
? ?static String UNSUPPORTED_OPERATION_IN_JCL_OVER_SLF4J = "http://www.slf4j.org/codes.html#unsupported_operation_in_jcl_over_slf4j";
?
? ?static LogFactory logFactory = new SLF4JLogFactory();

? 4)、如果我們要引入其他框架?一定要把這個框架的默認日志依賴移除掉?

? Spring框架用的是commons-logging;

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

==SpringBoot能自動適配所有的日志,而且底層使用slf4j+logback的方式記錄日志,引入其他框架的時候,只需要把這個框架依賴的日志框架排除掉即可;==

4、日志使用;

1、默認配置

SpringBoot默認幫我們配置好了日志;

//記錄器
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void contextLoads() {
//System.out.println();
//日志的級別;
//由低到高 ? trace<debug<info<warn<error
//可以調整輸出的日志級別;日志就只會在這個級別以以后的高級別生效
logger.trace("這是trace日志...");
logger.debug("這是debug日志...");
//SpringBoot默認給我們使用的是info級別的,沒有指定級別的就用SpringBoot默認規定的級別;root級別
logger.info("這是info日志...");
logger.warn("這是warn日志...");
logger.error("這是error日志...");
}
日志輸出格式:%d表示日期時間,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%logger{50} 表示logger名字最長50個字符,否則按照句點分割。 %msg:日志消息,%n是換行符-->%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n

SpringBoot修改日志的默認配置

logging.level.com.atguigu=trace
#logging.path=
# 不指定路徑在當前項目下生成springboot.log日志
# 可以指定完整的路徑;
#logging.file=G:/springboot.log
?
# 在當前磁盤的根路徑下創建spring文件夾和里面的log文件夾;使用?spring.log 作為默認文件
logging.path=/spring/log
?
# 在控制臺輸出的日志的格式
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n
# 指定文件中日志輸出的格式
logging.pattern.file=%d{yyyy-MM-dd} === [%thread] === %-5level === %logger{50} ==== %msg%n
logging.filelogging.pathExampleDescription
(none)(none)?只在控制臺輸出
指定文件名(none)my.log輸出日志到my.log文件
(none)指定目錄/var/log輸出到指定目錄的 spring.log 文件中

2、指定配置

給類路徑下放上每個日志框架自己的配置文件即可;SpringBoot就不使用他默認配置的了

Logging SystemCustomization
Logbacklogback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy
Log4j2log4j2-spring.xml or log4j2.xml
JDK (Java Util Logging)logging.properties

logback.xml:直接就被日志框架識別了;

logback-spring.xml:日志框架就不直接加載日志的配置項,由SpringBoot解析日志配置,可以使用SpringBoot的高級Profile功能

<springProfile name="staging">
? ?<!-- configuration to be enabled when the "staging" profile is active -->
可以指定某段配置只在某個環境下生效
</springProfile>

如:

<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
? ? ? ?<!--
? ? ? ?日志輸出格式:
%d表示日期時間,
%thread表示線程名,
%-5level:級別從左顯示5個字符寬度
%logger{50} 表示logger名字最長50個字符,否則按照句點分割。
%msg:日志消息,
%n是換行符
? ? ? ?-->
? ? ? ?<layout class="ch.qos.logback.classic.PatternLayout">
? ? ? ? ? ?<springProfile name="dev">
? ? ? ? ? ? ? ?<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ----> [%thread] ---> %-5level %logger{50} - %msg%n</pattern>
? ? ? ? ? ?</springProfile>
? ? ? ? ? ?<springProfile name="!dev">
? ? ? ? ? ? ? ?<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} ==== [%thread] ==== %-5level %logger{50} - %msg%n</pattern>
? ? ? ? ? ?</springProfile>
? ? ? ?</layout>
? ?</appender>

如果使用logback.xml作為日志配置文件,還要使用profile功能,會有以下錯誤

no applicable action for [springProfile]

5、切換日志框架

可以按照slf4j的日志適配圖,進行相關的切換;

slf4j+log4j的方式;


<dependency>
?<groupId>org.springframework.boot</groupId>
?<artifactId>spring-boot-starter-web</artifactId>
?<exclusions>
? ?<exclusion>
? ? ?<artifactId>logback-classic</artifactId>
? ? ?<groupId>ch.qos.logback</groupId>
? ?</exclusion>
? ?<exclusion>
? ? ?<artifactId>log4j-over-slf4j</artifactId>
? ? ?<groupId>org.slf4j</groupId>
? ?</exclusion>
?</exclusions>
</dependency>
?
<dependency>
?<groupId>org.slf4j</groupId>
?<artifactId>slf4j-log4j12</artifactId>
</dependency>

?

?

切換為log4j2


? <dependency>
? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ?<artifactId>spring-boot-starter-web</artifactId>
? ? ? ? ? ?<exclusions>
? ? ? ? ? ? ? ?<exclusion>
? ? ? ? ? ? ? ? ? ?<artifactId>spring-boot-starter-logging</artifactId>
? ? ? ? ? ? ? ? ? ?<groupId>org.springframework.boot</groupId>
? ? ? ? ? ? ? ?</exclusion>
? ? ? ? ? ?</exclusions>
? ? ? ?</dependency>
?
<dependency>
?<groupId>org.springframework.boot</groupId>
?<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

?web配置開發

?

SpringMVC自動配置

https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications

1. Spring MVC auto-configuration

Spring Boot 自動配置好了SpringMVC

以下是SpringBoot對SpringMVC的默認配置:==(WebMvcAutoConfiguration)==

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • 自動配置了ViewResolver(視圖解析器:根據方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉發?重定向?))

    • ContentNegotiatingViewResolver:組合所有的視圖解析器的;

    • 如何定制:我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來;

  • Support for serving static resources, including support for WebJars (see below).靜態資源文件夾路徑,webjars

  • Static index.html support. 靜態首頁訪問

  • Custom Favicon support (see below). favicon.ico

    ?

  • 自動注冊了 of Converter, GenericConverter, Formatter beans.

    • Converter:轉換器; public String hello(User user):類型轉換使用Converter

    • Formatter 格式化器; 2017.12.17===Date;

@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的規則
public Formatter<Date> dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化組件
}

? ==自己添加的格式化器轉換器,我們只需要放在容器中即可==

  • Support for HttpMessageConverters (see below).

    • HttpMessageConverter:SpringMVC用來轉換Http請求和響應的;User---Json;

    • HttpMessageConverters 是從容器中確定;獲取所有的HttpMessageConverter;

      ==自己給容器中添加HttpMessageConverter,只需要將自己的組件注冊容器中(@Bean,@Component)==

      ?

  • Automatic registration of MessageCodesResolver (see below).定義錯誤代碼生成規則

  • Automatic use of a ConfigurableWebBindingInitializer bean (see below).

    ==我們可以配置一個ConfigurableWebBindingInitializer來替換默認的;(添加到容器)==

    初始化WebDataBinder;
    請求數據=====JavaBean;

org.springframework.boot.autoconfigure.web:web的所有自動場景;

If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

2、擴展SpringMVC

? ?<mvc:view-controller path="/hello" view-name="success"/>
? ?<mvc:interceptors>
? ? ? ?<mvc:interceptor>
? ? ? ? ? ?<mvc:mapping path="/hello"/>
? ? ? ? ? ?<bean></bean>
? ? ? ?</mvc:interceptor>
? ?</mvc:interceptors>

==編寫一個配置類(@Configuration),是WebMvcConfigurerAdapter類型;不能標注@EnableWebMvc==;

既保留了所有的自動配置,也能用我們擴展的配置;

//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
?
? ?@Override
? ?public void addViewControllers(ViewControllerRegistry registry) {
? ? ? // super.addViewControllers(registry);
? ? ? ?//瀏覽器發送 /atguigu 請求來到 success
? ? ? ?registry.addViewController("/atguigu").setViewName("success");
? }
}

原理:

? 1)、WebMvcAutoConfiguration是SpringMVC的自動配置類

? 2)、在做其他自動配置時會導入;@Import(EnableWebMvcConfiguration.class)


? ?@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
? ? ?private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
?
//從容器中獲取所有的WebMvcConfigurer
? ? ?@Autowired(required = false)
? ? ?public void setConfigurers(List<WebMvcConfigurer> configurers) {
? ? ? ? ?if (!CollectionUtils.isEmpty(configurers)) {
? ? ? ? ? ? ?this.configurers.addWebMvcConfigurers(configurers);
? ? ? ? ? //一個參考實現;將所有的WebMvcConfigurer相關配置都來一起調用; ?
? ? ? ? ? @Override
? ? ? ? ? ? // public void addViewControllers(ViewControllerRegistry registry) {
? ? ? ? ? ? ?// ? for (WebMvcConfigurer delegate : this.delegates) {
? ? ? ? ? ? ? // ? ? ? delegate.addViewControllers(registry);
? ? ? ? ? ? ? // ? }
? ? ? ? ? ? }
? ? ? ? }
}

? 3)、容器中所有的WebMvcConfigurer都會一起起作用;

? 4)、我們的配置類也會被調用;

? 效果:SpringMVC的自動配置和我們的擴展配置都會起作用;

3、全面接管SpringMVC;

SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置;所有的SpringMVC的自動配置都失效了

我們需要在配置類中添加@EnableWebMvc即可;


//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
?
? ?@Override
? ?public void addViewControllers(ViewControllerRegistry registry) {
? ? ? // super.addViewControllers(registry);
? ? ? ?//瀏覽器發送 /atguigu 請求來到 success
? ? ? ?registry.addViewController("/atguigu").setViewName("success");
? }
}

原理:

為什么@EnableWebMvc自動配置就失效了;

1)@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {

2)、

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

3)、

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//容器中沒有這個組件的時候,這個自動配置類才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

4)、@EnableWebMvc將WebMvcConfigurationSupport組件導入進來;

5)、導入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;

?

5、如何修改SpringBoot的默認配置

模式:

? 1)、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果有就用用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來;

? 2)、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置

? 3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定制配置

RestfulCRUD

?

轉載于:https://www.cnblogs.com/gdfs/p/10876874.html

總結

以上是生活随笔為你收集整理的SpringBoot基础篇的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。