SpringBoot學習筆記(二)

一、SpringBoot

1,SpringBoot簡介

	Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成爲領導者。
	Spring框架是Java平臺的一種開源框架,提供有控制反轉特性的容器(ioc容器),ioc旨在方便項目維護和測試,他提供一種通過Java的反射機制對Java的對象進行統一的配置和管理的方法,同時通過ioc容器管理對象的生命週期,通過掃描xml文件或類上特定Java註解來配置對象,程序員可以通過依賴查找和依賴注入來獲取對象。springAop框架基於代理模式,aop框架針對模塊之間的交叉點進行模塊化。spring框架下的事務管理,遠程訪問等功能均可以通過使用SpringAOP技術實現,spring的事務管理框架爲Java平臺帶來了一種抽象機制,使所有的事務能夠與保存點一起工作,並且可以在
	在 Spring 體系中,Spring Boot JPA 就是約定優於配置最佳實現之⼀,不需要關注表結構,我們約定類名即是表名,屬性名即是表的字段,String 對應 varchar,long 對應 bigint,只有需要⼀些特殊要求的屬性,我們再單獨進⾏配置,按照這個約定我們可以將以前的⼯作⼤⼤的簡化。Spring Boot 體系將約定優於配置的思想展現得淋淋盡致,⼩到配置⽂件,中間件的默認配置,⼤到內置容器、⽣態中的各種 Starters ⽆不遵循此設計規則。Spring Boot ⿎勵各軟件組織⽅創建⾃⼰的 Starter,創建
Starter 的核⼼組件之⼀就是 autoconfigure 模塊,也是 Starter 的核⼼功能,在啓動的時候進⾏⾃動裝配,屬
性默認化配置。
	可以說正是因爲 Spring Boot 簡化的配置和衆多的 Starters 才讓 Spring Boot 變得簡單、易⽤、快速上⼿,也可以說正是約定優於配置的思想的徹底落地才讓 Spring Boot ⾛向輝煌。Spring Boot 約定優於配置的思想讓Spring Boot 項⽬⾮常容易上⼿,讓編程變的更簡單,其實編程本該很簡單,簡單纔是編程的美。

2,微服務

微服務:架構風格
一個應用是一組小型服務:可以通過hTTP的方式進行互通
單體應用:每一個功能元素最後都是可以獨立升級替換的服務單元

3,環境約束

jdk 推薦1.7及以上
maven 推薦3.3及以上
Intellij IDEA sts
spring Boot1.5.9

4,SpringBoot helloworld

1,創建一個maven工程
2,導入springboot相關依賴
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
3,編寫一個主程序
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloWorldApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloWorldApplication.class,args);

    }
}

5,springboot 探究hello world

1,父項目

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
 </parent>
 他的父項目 。。。。。
 

導入依賴有默認版本不需要導入版本號

沒有在dependencies裏面管理的需要導入版本號

2,導入依賴

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

spring-boot-starter:springboot的場景啓動器,導入了web的依賴版本模塊

springboot將所有的功能場景都抽取出來,做成一個starter啓動器,使用時導入相關場景啓動器。

3,主程序類,入口類

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class HelloWorldApplication {
    public static void main(String[] args) {
        SpringApplication.run(HelloWorldApplication.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 {

@SpringBootApplication註解的配置類

標註在某個類上表示這是一個springboot配置類

@Configuration:配置類上來標註這個註解;

配置類–配置文件;配置類也是容器中的額一個組件;@Component

@EnableAutoConfiguration 開啓自動配置功能

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage 自動配置包

@Import({Registrar.class})
spring的底層導入註解@import給容器中導入一個組件:導入的組件Registrar.class
將主配置類(@SpringBootApplication標註的類)的包以及下面所有子包掃描進配置類
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({Registrar.class})
public @interface AutoConfigurationPackage {
}

@Import({AutoConfigurationImportSelector.class})

給容器中導入組件,導入的就是後面的類的組件

導入的組件以全路徑類名的方式返回,這些組件就會被添加到容器中

會給容器導入非常多層次的自動配置類:XXXAutoConfiguration就是給容器中導入自動配置的組件在這裏插入圖片描述

6,SpringInitializer快速創建springboot項目

在這裏插入圖片描述

在這裏插入圖片描述

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-m84nftHt-1570796360110)(D:\Documents\Scrshot\2019-09-26_150808.png)]

默認生成的springboot項目

主程序已經生成好了,我們只需要我們自己的邏輯

resource文件夾的目錄架構

​ static保存靜態資源:js/css/image

​ templates:保存所有的模板頁面 :(spring Boot默認jar包使用嵌入式的tomcat)可以使用模板引擎

​ application.properties:springboot應用的配置文件

二、配置文件

1、配置文件

springboot使用的是一個全局的我配置文件,配置文件名是固定的

application.properties

application.yml

配置文件的作用,就是修改springboot的默認值

yaml(yaml ain`t Markup language)

標記語言

​ 以前的配置文件都是XXX.xml

properties:

	server.port=8080;

yml

	server:  
​		port: 8081

xml

<server>
	<port>8082</port>
</server>

2、yml語法

1,基本語法

K: V表示一對鍵值對(空格必須要)

以空格的縮進來控制層級關係:只要是左對齊的一列數據,都是一個層級的

	server:  
​		port: 8081
		path:/hello

2,值的寫法

字面量:普通的值(數字,字符串,布爾)

k:v字面直接來寫字符串不用加引號

“”:雙引號 不會轉義特殊字符\n—>換行

‘’:單引號 會轉義特殊字符 \n—>\n

對象 Map(屬性和值)(鍵值對)

k:v 對象還是這種方式

friend:

​	lastName: zhangsan

​	age: 20

行內寫法

friend: {lastName: zhangsan,age: 20}

數組(list,set)

用-短橫線表示數組中的一個元素

pets:
-cat
-dog

行內寫法

pets: [cat,dog]

3,@value獲取值和@ConfigurationProperties獲取值比較

@ConfigurationProperties @value
功能 批量注入 單個注入
鬆散語法 支持 不支持
SpEL 不支持 支持
JSR303數據校驗 支持 不支持
複雜類型封裝 支持 不支持

配置文件yml還是properties都能獲取到值

如果說,我們只是在配置文件中獲取某個值使用@Value來何配置文件

如果說,我們專門編寫一個JavaBean,我們就直接使用@ConfigurationProperties

/*
* 將配置文件的值映射到配置文件中(
* @ConfigurationProperties 把配文件的值和Person的屬性進行綁定
* */
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
   // @Value("${person.last-name}")
    private String lastName;

@PropertySource加載制定配置文件&@ImportSource

@PropertySource

@PropertySource(value = {"classpath:application.properties"})
@Component
@ConfigurationProperties(prefix = "person")

@ImportSource導入spring配置文件 讓裏面的內容生效

Spring Boot裏面沒有spring的配置文件,我們自己寫的也沒辦法生效

@ImportResource(locations = {"classpath:beans.xml"})

Spring Boot推薦添加組件方式

推薦使用全註解的方式

<?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.xja.hellodemo2.demo.service.HelloService"></bean>
</beans>

1配置類====spring配置文件

/*
* @Configuration當前類是個配置類
* <bean>添加
* */
@Configuration
public class MyAppConfig {
//將方法的返回值添加到容器中,容器中這個組件默認id就是方法名
    @Bean
    public HelloService helloService(){
        System.out.println("成了");
        return new HelloService();
    }

}

4、配置文件佔位符

1、隨機數

person.last-name= zhangsan${random.uuid};
person.age=${random.int}
//隨機數

2、佔位符獲取之前配置的值,如果沒有:默認值

person.dog.name=${person.hello:hello}_dog
//默認值

5、profile

1、可以創建多個profile文件

文件名可以是application.{profile}.properties/yml

默認使用application.properties的配置

2、yml支持多文檔塊方式

server:

port: 8089

spring:

profiles:

​ active: dev


3、激活制定profile

在默認配置文件中

spring.profiles.active=dev

命令行激活

jar包激活

在這裏插入圖片描述
虛擬機參數激活

-Dspring.profiles.active=dev

6、配置文件加載位置

在這裏插入圖片描述

優先級高的會覆蓋優先級低的配置,

同時四個位置的配置全部加載主配置文件:互補配置,高的有聽高的,高的沒有聽低的,高低都沒有都不用

我們還可以通過spring.config.location來改變默認的配置文件位置 項目打包好,使用命令行參數的形式制定配置文件的位置,配置共同起作用。

7、外部配置加載

在這裏插入圖片描述

springboot也可以從下往上加載配置,優先級從高到低優。先級 互補

1,命令行參數

java -jar demo-0.0.1-SNAPSHOT.jar --server.port=8087( --server.path)

當我們指定加載配置文件的時候,優先加載帶profile的配置文件(無論是否是在jar包內)由jar包外向jar包內加載

再加載不帶profile的配置文件

8、自動配置原理

1,springBoot啓動時加載主配置類開啓自動掃描
@EnableAutoConfiguration
利用@EnableAutoConfigurationSelector給容器中導入一些組件
可以插件selectImports()方法內容
List<String> Configurations = getCandldateConfigurations(annotationMetadata,arributes);獲取候選的配置
SpringFactoriesLoader.loadFactoryNames()
掃描所有jar包類路徑下 META—INF/spring.factories
把掃面到的這些文件的內容包裝成properties對象
從properties中獲取到EnableAutoConfiguration.class類對應的值,然後把他們添加在容器中

在這裏插入圖片描述
先把這些自動配置類加載到容器中

每一個自動配置類進行自動配置功能

以HttpEncodingAutoConfiguration爲列解釋自動配置原因

@Configuration //這是一個配置類==配置文件 給容器中添加組件
@EnableConfigurationProperties({HttpProperties.class})//啓用指定類的ConfigurationProperties功能,把配置文件中的值綁定
@ConditionalOnWebApplication(
    type = Type.SERVLET
)//spring底層conditional註解,根據不同條件,看是否讓配置文件生效
@ConditionalOnClass({CharacterEncodingFilter.class})//判斷當前項目有沒有該類
@ConditionalOnProperty(
    prefix = "spring.http.encoding",
    value = {"enabled"},
    matchIfMissing = true
)//判斷配置文件中是否存在某個配置 spring.http.encoding
//即使我們配置文件中不配置 也默認生效
public class HttpEncodingAutoConfiguration {
    private final Encoding properties;//已經跟springboot映射了
    
    
    //只有一個有參構造器的情況下,參數值就會從容器中拿
     public HttpEncodingAutoConfiguration(HttpProperties properties) {
        this.properties = properties.getEncoding();
    }
    @Bean//給容器中添加組件,這個組件的某些值需要從properties中獲取
    @ConditionalOnMissingBean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE));
        return filter;
    }

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

配置文件配置的屬性值都是在XXXproperties文件中

精髓:

1,springBoot啓動會加載大量的自動配置類

2,我們看我們需要功能有沒有spring boot默認寫好的自動配置類;

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

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

AutoConfiguration:自動配置類,給容器添加組件

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

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

debug=true屬性查看

打印自動配置報告

三、日誌

1、日誌框架

市面上的日誌框架

JUL,JCL,JBoss-logging,Log4j,Log4j2,slf4j

在這裏插入圖片描述

日誌門面:SLF4j;

日誌實現:logback

spring boot:底層spring框架,使用JCl

2、SLF4j使用

1、如何在系統中使用SLF4J

以後開發的時候,日誌記錄方法的調用

給系統導包SLF4j和logback

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

在這裏插入圖片描述

2、遺留問題

a(slf4j+logback):spring(commons-logging)、、、、其他框架的日誌不同

這時就需要統一日誌信息

在這裏插入圖片描述
如何讓系統中所有的日誌都統一到slf4j

1、將系統中其他日誌框架先排除

2、替換原有的日誌框架包

3、springboot 裏面的日誌關係

在這裏插入圖片描述

如果我們想導入一個新的框架的時候,一定要把原本的日誌包剔除

<dependency>
      <groupId>org.subethamail</groupId>
      <artifactId>subethasmtp</artifactId>
      <version>2.1.0</version>
      <scope>test</scope>
      <exclusions>
        <exclusion>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>

springboot能自動適配所有日誌

4、日誌使用

1、默認配置

//記錄器
    Logger logger = LoggerFactory.getLogger(getClass());

    @Test
    public void contextLoads()
    {
        //日誌級別
        //由低到高 trace<debug<info<warn<error
        //可以調整輸出的日誌級別
        logger.trace("這是trace日誌");
        logger.debug("這是debug日誌");
        //springboot默認給我們設置的是info級別的
        logger.info("這是info日誌");
        logger.warn("這是warn日誌");
        logger.error("這是error日誌");
    }
    此時測試輸出的有
    這是info日誌
    這是warn日誌
    這是error日誌

spring boot默認級別爲info

如果要改變默認級別,我們可以通過在配置文件中修改配置屬性eg:logging.level.com.xja=trace

此時測試輸出就有

這是trace日誌
這是debug日誌
這是info日誌
這是warn日誌
這是error日誌

生成日誌文件

有路徑就去路徑處生成,沒路徑就在項目下生成

logging.file=springboot.file

logging.file=d:/springboot.file

跟目錄下生成

logging.path=/spring/log

在控制檯輸出的日誌輸出的格式

logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss}[%thread] [%level] %logger{50}- %m%n

制定文件中日誌輸出的格式

logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss}======[%thread] [%level] %logger{50}- %m%n

<encoder>表示對日誌進行編碼:
%d{HH: mm:ss.SSS}——日誌輸出時間
%thread——輸出日誌的進程名字,這在Web應用以及異步任務處理中很有用
%-5level——日誌級別,並且使用5個字符靠左對齊
%logger{36}——日誌輸出者的名字
%msg——日誌消息
%n——平臺的換行符 
ThresholdFilter爲系統定義的攔截器,例如:我們用ThresholdFilter來過濾掉ERROR級別以下的日誌不輸出到文件中,可以保證文件裏只有Error級別日誌。

2、指定配置

給類路徑下放上每個日誌框架自己的配置文件即可,spring boot就不使用他默認配置的

Logging System Customization
Logback logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2 log4j2-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>

<springProfile name="dev | staging">
//可以指定某個配置只在多個環境下才生效
	<!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>

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

在這裏插入圖片描述

3、切換配置

1,剔除舊的依賴日誌包,導入新的依賴,可以直接通過依賴樹操作,再導入新的配置文件

2、剔除舊的包,導入新的依賴

<dependency>    
	<groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j2</artifactId>
</dependency>

四、web開發

1、簡介

springboot使用

1,創建springboot工程

2、選擇對應的依賴環境

2、springboot對於靜態資源的映射規則

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {
    //可以設置和靜態資源有關的參數 緩存時間等
@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}

1,所有的web jar包都會去classpath:/META-INF/resources/webjars/ 路徑下找

以jar包的方式引入靜態資源

www.webjars.org

		//訪問的時候只需要寫出webjars下面的資源路徑
		<dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

2、“/**”表示訪問當前任何路徑

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",      "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

3、主頁面,靜態資源文件下所有的index.html文件都被"/**"映射

localhost:8080/

4、所有的**/favicon.ico都是在靜態資源文件下找;

3、模板引擎

1、引入thymaler

jsp,velocity,freemarker,thymaler

在這裏插入圖片描述

springboot推薦thymeleaf 語法簡單 功能強大

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

換thymeleaf版本

<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>

2、thymeleaf語法

默認規則

private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";
//只需要把頁面放在classpath:/templates/路徑下

使用

1、導入thymeleaf的名稱空間

<html lang="en" xmlns:th"http://http:www.thymeleaf.org">
    
</html>
<div id="div1" th:id="${hello}" th:text="${success}"></div>

在這裏插入圖片描述

//表達式
Simple expressions:表達式語法
    Variable Expressions: ${...}
    //獲取對象屬性
    //調用方法
    //使用內置的基本對象
    Selection Variable Expressions: *{...}
    Message Expressions: #{...}
    Link URL Expressions: @{...}
    Fragment Expressions: ~{...}
Literals
Text literals: 'one text' , 'Another one!' ,…
Number literals: 0 , 34 , 3.0 , 12.3 ,…
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,…
Text operations:
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:
Binary operators: + , - , * , / , %
Minus sign (unary operator): -
Boolean operations:
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
Page 17 of 106
No-Operation: _

eg:

<body>
    <div id="div1" th:id="${hello}" th:text="${hello}"></div>
    <div th:text="${hello}"></div>
    <div th:utext="${hello}"></div>
    <div th:text="${list}" th:each="list:${list}"></div>
    <div th:each="list:${list}">[[${list}]]</div>
</body>
@RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","<h1>你好<h1/>");
        map.put("list", Arrays.asList("zhangsan","lisi"));
        return "success";

    }

: -
Boolean operations:
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
Page 17 of 106
No-Operation: _


eg:

```html
<body>
    <div id="div1" th:id="${hello}" th:text="${hello}"></div>
    <div th:text="${hello}"></div>
    <div th:utext="${hello}"></div>
    <div th:text="${list}" th:each="list:${list}"></div>
    <div th:each="list:${list}">[[${list}]]</div>
</body>
```

~~~java
@RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","<h1>你好<h1/>");
        map.put("list", Arrays.asList("zhangsan","lisi"));
        return "success";

    }

3、spring boot中的springmvc自動配置

27.1.1 Spring MVC auto-configuration
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.

The auto-configuration adds the following features on top of Spring’s defaults:

Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
//視圖解析器
Support for serving static resources, including support for WebJars (see below).
Automatic registration of Converter, GenericConverter, Formatter beans.
//轉換器Converter
//格式化Formatter  可以在文件這中配置格式化組件
Support for  s (see below).//轉換http請求
Automatic registration of MessageCodesResolver (see below).
Static index.html support.
Custom Favicon support (see below).
Automatic use of a ConfigurableWebBindingInitializer bean (see below).
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.

4、如何修改springboot默認配置

1、模式

​ 1、springboot在自動配置很多組件的時候,先看容器有沒有用戶自己的配置(@Bean、@Component)如果用戶有,就用,如果沒有就用自己默認的

2、擴展springMVC

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

編寫一個配置類 ,是webMvcConfigurationAdapt類型 不能標註@EnableWebMvc

在這裏插入圖片描述
原理:

1,webmvcautoconfiguration是springmvc的v 自動配置類

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

3、容器中所有的WebMvcConfigure都會一起起作用

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

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

3、全面接管springMvc

springboot對springMvc自動配置不要了,所有的自己配

只需要在配置類上添加一個@EnableWebMvc

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章