SpringBoot文檔

1、Spring Boot 入門

一、Hello World探究

一、POM文件

一、父項目

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.0.5.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
</parent>
他的父項目是
<parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-dependencies</artifactId>
       <version>2.0.5.RELEASE</version>
       <relativePath>../../spring-boot-dependencies</relativePath>
</parent>
他來真正管理Spring Boot 應用裏面的全部依賴版本:

Spring Boot 版本仲裁中心:css

之後咱們導入依賴默認是不須要寫版本:(沒有在dependencies裏面管理的依賴天然須要寫版本號)html

二、啓動器

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

spring-boot-starter-web: Spring Boot 場景啓動器幫咱們導入了Web模塊正常運行所依賴的組件;java

Spring Boot 將全部相關場景都抽取出來,作成一個個的starters(啓動器),只須要在項目裏面引入這些starters相關場景的全部依賴都會導入進來。要用什麼功能就導入什麼場景的啓動器react

二、主程序類、注入口類

/*
* @SpringBootApplication 來標註一個主程序類,說明這是一個Spring Boot 應用
*/
@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
      //spring應用啓動起來
     SpringApplication.run(DemoApplication.class, args);
  }
}

@SpringBootApplication :Spring Boot 應用標註在某個類上說明這個類是SpringBoot的主配置類,jquery

SpringBoot就應該運行這個類的main方法來啓動SpringBoot應用;web

@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 {

@SpringBootConfiguration:Spring Boot 的配置類;redis

標註在某個類上,表示這是一個Spring Boot 的配置類;spring

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

配置類-------配置文件:配置類也是容器中的一個組件;@Componentexpress

@EnableAutoConfiguration:開啓自動配置功能;

之前咱們須要配置的東西,spring Boot 幫咱們自動配置;@EnableAutoConfiguration

告訴Spring Boot 開啓自動配置功能;這樣自動配置才能生效;

@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage:自動配置包

@Import(AutoConfigurationPackages.Registrar.class);

spring的底層註解@import,給容器中導入一個組件;導入的組件由

AutoConfigurationPackages.Registrar.class

==將主配置類(@SpringBootApplication標註的類)的所在包及下面全部子包裏面的全部組件掃描到Spring容器;==

@Import(AutoConfigurationImportSelector.class)

給容器中導入組件?

AutoConfigurationImportSelector:導入哪些組件的選擇器;

將全部須要導入的組件以全類名的方式返回;這些組件就會被添加到容器中;

會給容器中導入很是多的自動配置類(xxxAutoConfiguration);就是給容器中導入這個場景所須要的全部組件,並配置好這些組件

 

有了自動配置類,免去了咱們手動編寫配置注入功能組件等的工做;

SpringFactoriesLoader.loadFactoryNames(EnableAutoConfiguration.class,classLoader);

==SpringBoot再啓動的時候從類路徑下的META-INF/spring.factories中獲取EnableAutoConfiguration指定的值,將這些值做爲自動配置類導入到容器中,自動配置類就生效,幫咱們進行自動配置工做;==;之前咱們須要本身配置的東西,自動配置類都幫咱們;

J2EE的總體整合解決方案和自動配置都在spring-boot-autoconfigure-2.0.5.RELEASE.jar;

二、使用Spring Initializer快速建立SpringBoot項目

IDE都支持使用Spring的項目建立嚮導快速建立一個Spring Boot項目;

選擇咱們須要的模塊;嚮導會聯網建立Spring Boot 項目;

默認生成的Spring Boot項目;

  • 主程序已經生成好了,咱們只須要咱們本身的邏輯

  • resources文件夾中目錄結構

    • static:保存全部的靜態資源;js css images ;

    • templates:保存全部的模板頁面;(Spring Boot 默認jar包使用嵌入式的Tomcat,默認不支持jsp頁面);可使用引擎模板(Freemarker、thymeleaf);

    • application.properties:Spring Boot 應用的配置文件;能夠修改一些默認配置;

 

2、 配置文件

一、配置文件

Spring Boot 使用一個全局的配置文件,配置文件名是固定的;

  • application.properties

  • application.yml

配置文件的做用:修改SpringBoot自動配置的默認值;SpringBoot再底層都給咱們自動配置好;

YAML(YAML Ain't Markup language)

YAML A Markup Language ;是一個標記語言;

YAML isn't Markup Language; 不是一個標記語言

標記語言:

之前的配置文件;大多使用的都是xxx.xml文件;

YAML:以數據爲中心,比json、xml等更適合作配置文件;

YAML:配置例子

server:
port: 8090

XML:

<server>
<port>8081</port>
</server>

二、YAML語法

一、基本語法

k:(空格)v:表示一對鍵值對(空格必須有);

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

server:
port: 8090
path: /hello

屬性和值也是大小寫敏感的;

二、值的寫法

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

K:V :字面直接來寫;

字符串默認不用加上單引號和雙引號;

「 」: 雙引號 ;不會轉義字符串裏面的特殊字符;特殊字符會做爲自己想表示的意思

name: "zhangsan \n lisi ":輸出:zhangsan 換行 lisi

‘ ’ :單引號;會轉義特殊字符,特殊字符最終只是一個普通的字符串數據

name: ‘zhangsan \n lisi ’ :輸出:zhangsan \n lisi

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

K:V:在下一行來寫對象的屬性和值的關係;注意縮進

對象仍是K:V 的方式

friends:
lastName:zhangsan
age :20

行內寫法:

friends:{lastName: zhangsan ,age :20}

 

數組(List、Set)

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

pets:
-cat
-dog
-pig

行內寫法

pets:{cat,dog,pig}

三、配置文件值注入

配置文件

person:
  lastName: zhangsan
  age: 18
  boss: false
  birth: 2018/10/4
  maps: {k1: v1, k2: 12}
  lists:
    -lisi
    -zhaoliu
  dog:
    name: 小狗
    age: 2

javaBean:

/*
*將配置文件中配置的每個屬性的值,映射到這個組件中
*@ConfigurationProperties:告訴springBoot將本類中的全部屬性和配置文件中相關配置進行綁定;
*       prefix = "person"配置文件中哪一個下面的全部屬性進行一一映射
* 只有這個組件是容器中的組件,才能使用容器提供的@ConfigurationProperties功能;
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
   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>

一、properties配置文件在idea中默認UTF-8可能會亂碼

 

 

二、@value獲取值和@ConfigurationProperties獲取值比較

  @CONFIGURATIONPROPERTIES @VALUE
功能 批量注入配置文件中的屬性 一個一個指定
鬆散綁定(鬆散語法) 支持 不支持
SpEL(表達式計算) 不支持 支持
JSR303數據校驗 支持 不支持
複雜類型封裝 支持 不支持

配置文件yml仍是properties他們都能獲取到值;

若是說,咱們只是在某和業務邏輯中須要獲取一下配置文件的某項值,使用@Value

若是說咱們專門編寫了一個javabean來和配置文件進行映射,咱們就直接使用@ConfigurationProperties;

 

三、配置文件注入值數據校驗

@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person {
   /*
   * <bean class="Persion">
   *     <property name ="lastName" value="字面量/${key}從環境變量,配置文件中獲取值/#{SpEl}"</property>
   * </bean>
   * */
//   @Value("${person.last-name}")
   @Email
   private String lastName;
 // @Value("#{11*2}")
   private Integer age;
   //@Value("true")

   private Boolean boss;
   private Date birth;

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

四、@PropertySource&@importResource

@PropertySoure:加載指定的配置文件

/*
*將配置文件中配置的每個屬性的值,映射到這個組件中
*@ConfigurationProperties:告訴springBoot將本類中的全部屬性和配置文件中相關配置進行綁定;
*       prefix = "person"配置文件中哪一個下面的全部屬性進行一一映射
*       默認從全局配置文件中獲取值;
* 只有這個組件是容器中的組件,才能使用容器提供的@ConfigurationProperties功能;
*/
@Component
@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})
//@Validated
public class Person {
   /*
   * <bean class="Persion">
   *     <property name ="lastName" value="字面量/${key}從環境變量,配置文件中獲取值/#{SpEl}"</property>
   * </bean>
   * */
//   @Value("${person.last-name}")
   @Email
   private String lastName;
 // @Value("#{11*2}")
   private Integer age;
   //@Value("true")

   private Boolean boss;

@importResource:導入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="org.wl.springboot.service.HelloService"></bean>
</beans>

SpringBoot 推薦給容器中添加組件的方式;

一、配置類=========Spring配置文件

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

/*
* @Configuration:指明當前類是一個配置文件;就是來替代以前的Spring配置文件
*在配置文件中用<bean></bean>標籤添加組件
*
* */

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

四、配置文件佔位符

一、隨機數

${random.uuid} ${random.int} ${random.long}
${random.int(10)} ${random.int[1024,65536]

二、佔位符獲取以前配置的值,若是沒有能夠是用:指定默認值

person:
  lastName: zhangsan ${random.uuid}
  age: ${random.int}
  boss: false
  birth: 2018/10/4
  maps: {k1: v1, k2: 12}
  lists:
    -lisi
    -zhaoliu
  dog:
    name: ${person.hello:hello}_dog
    age: 2

五、Profile

一、多Profile文件

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

默認使用application.properties的配置;

 

二、yml支持多文檔塊方式

server:
port: 8090
spring:
profiles:
  active: dev
---

server:
port: 8003
spring:
profiles: dev
---

server:
port: 8004
spring:
profiles: prod

---

 

三、激活指定profile

一、在配置文件中指定Spring.properties.active =dev

二、命令行:

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

能夠直接在測試的時候,配置傳入命令行參數

三、 虛擬機參數:

-Dspring.profile.active=dev

六、配置文件加載位置

SpringBoot 啓動會掃描一下位置的application.properties或者application.yml文件做爲Spring Boot 的默認配置

文件

-file:/config/

-file:/

-classpath:/config/

-classpath:/

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

SpringBoot會從這四個位置所有加載主配置文件;互補配置

==spring-boot配置文件中server.context-path=/XXXXXXX不起做用:==

==緣由是更新後寫法變成了`server.servlet.context-path=/XXXXXX,這樣寫便可==

 

==咱們還能夠經過spring.config.location來改變默認的配置文件位置==

項目打包好之後,咱們可使用命令行參數的形式,啓動項目的時候來指定配置文件的新位置;指定配置文件和默認加載的這些配置文件共同起做用造成互補配置

java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --spring.config.location=C:\Users\80481\Desktop\application.properties

七、外部配置加載順序

SpringBoot也能夠從如下位置加載配置:按照優先級從高到低;高優先級的配置覆蓋低優先級的配置,全部配置會造成互補配置

  1. 命令行參數

    • 全部的配置均可以在命令行上進行指定;

    • 多個配置用空格分開; –配置項=值

    java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar 
    --server.port=8087 --server.context-path=/abc
    1234

    2.來自java:comp/env的JNDI屬性 3.Java系統屬性(System.getProperties()) 4.操做系統環境變量 5.RandomValuePropertySource配置的random.*屬性值


    6.jar包外部的application-{profile}.properties或application.yml(帶spring.profile)配置文件 7.jar包內部的application-{profile}.properties或application.yml(帶spring.profile)配置文件 8.jar包外部的application.properties或application.yml(不帶spring.profile)配置文件 9.jar包內部的application.properties或application.yml(不帶spring.profile)配置文件

    由jar包外向jar包內進行尋找,優先加載待profile的,再加載不帶profile的。1

    10.@Configuration註解類上的@PropertySource 11.經過SpringApplication.setDefaultProperties指定的默認屬性

    全部的配置加載來源;

    參考官方文檔

八、自動配置原理

配置文件到底能寫什麼?怎麼寫?自動配置原理;

配置文件能配置的屬性參照

一、自動配置原理

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

2)、@EnableAutoConfiguration做用:

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

  •  

  • 能夠查看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,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.core.ReactorCoreAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityRequestMatcherProviderAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
org.springframework.boot.autoconfigure.session.NonUniqueSessionRepositoryFailureAnalyzer

# Template availability providers
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,\
org.springframework.boot.autoconfigure.web.servlet.JspTemplateAvailabilityProvider

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

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

4)、以HttpEncodingAutoConfigurationHttp編碼自動配置)爲例解釋自動配置原理;

@Configuration//表示這是一個配置類,之前編寫的配置文件同樣,也能夠給容器中添加組件
@EnableConfigurationProperties(HttpEncodingProperties.class)//啓用ConfigurationProperties功能;將配置文件中對應的值和HttpEncidingproperties綁定起來;並把HttpEncodingProperties加入到ioc容器中

@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)//spring底層@Conditional註解,根據不一樣的條件,若是知足指定條件,整個配置文件裏面的配置就會生效;判斷當前應用是不是WEB應用,若是是,當前配置類生效
@ConditionalOnClass(CharacterEncodingFilter.class)//判斷當前項目有沒有這個類
//CharacterEncodingFilter;springmvc中進行亂碼解決的過濾器
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)//判斷配置文件中是否存在某個配置spring.http.encoding.enabled;若是不存在,判斷也是成立的
//即便咱們配置文件中不配置spring.http.encoding.enabled=true,也是默認生效的;
public class HttpEncodingAutoConfiguration {
   
   //他已經和SpringBoot的配置文件映射了
   private final HttpEncodingProperties properties;
   
   //只有一個有參構造器的狀況下,參數的值就會從容器中拿
   public HttpEncodingAutoConfiguration(HttpEncodingProperties properties){
this.properties = properties;
}

   
   @Bean//給容器中添加一個組件,這個組件中的某些值須要從properties中獲取
@ConditionalOnMissingBean//判斷容器中沒有這個組件?
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 = StandardCharsets.UTF_8;
精髓

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

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

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

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

xxxxAutoConfigurartion:自動配置類;

給容器中添加組件

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

二、細節

一、@conditional派生註解(spring註解版原生的@conditional做用)

做用:必須是@Conditional指定的條件成立,纔給容器中添加組件,配置文件裏面的配置內容纔會生效;

 

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

咱們怎麼知道哪些自動配置類生效了?

咱們能夠經過啓用debug=true屬性;來讓控制檯打印自動配置報告,這樣咱們就知道哪些自動配置類生效;

 

============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:(自動配置類啓用的)
-----------------

  CodecsAutoConfiguration matched:
     - @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
  CodecsAutoConfiguration.JacksonCodecConfiguration matched:
     - @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
         
Negative matches:(沒有啓動,沒有匹配成功的自動配置類)
-----------------

  ActiveMQAutoConfiguration:
     Did not match:
        - @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)

  AopAutoConfiguration:
     Did not match:
        - @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice', 'org.aspectj.weaver.AnnotatedElement' (OnClassCondition)

3、日誌

一、日誌框架

小張:開發一個大型系統:

一、System.out.println("");將關鍵數據打印在控制檯:去掉?寫在一個文件?

二、框架來記錄系統的一些運行時信息;日誌框架;zhanglogging.jar;

三、高大上的幾個功能?異步模式?自動歸檔?xxxx?zhanglogging-good.jar?

四、將之前框架卸下來?換上了新的框架,從新修改以前相關的API;zhanglogging-prefect.jar;

五、JDBC---數據庫驅動;

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

給項目中導入具體的日誌實現就好了;咱們以前的日誌框架都是實現的抽象層;

市面上的日誌框架;

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

 

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

日誌門面:SLF4J;

日誌實現:Logback;

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

SpringBoot 選用SLF4J和logback;

二、SLF4J使用

一、如何在系統中使用SLF4J

之後開發的時候,日誌記錄方法的調用,不該該直接調用日誌的實現類,而是調用日誌抽象層裏面的方法;

給系統裏面導入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之後,配置文件仍是作成日誌實現框架本身自己的配置文件

二、遺留問題

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

統一日誌記錄,即便是別的框架和咱們一塊兒統一使用slf4j進行輸出?

如何讓系統中全部的日誌都統一到Slf4j;

==一、將系統中其餘日誌框架先排除出去;==

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

==三、咱們導入slf4其餘的實現==

三、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>
 <version>2.0.5.RELEASE</version>
 <scope>compile</scope>
</dependency>

SpringBoot底層依賴關係

 

總結:

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

2)、SpringBoot也把其餘的日誌都替換了成了slf4j;

3)、中間替換包?

public final class LoggerFactory {

   static final String CODES_PREFIX = "http://www.slf4j.org/codes.html";

   static final String NO_STATICLOGGERBINDER_URL = CODES_PREFIX + "#StaticLoggerBinder";

 

4)、若是咱們引入其餘框架?必定要把這個框架的默認日誌依賴移除掉?

Spring框架用的是commons-logging;

 

SpringBoot能自動適配全部的日誌,並且底層使用slf4j+logback的記錄方式記錄日誌,引入其餘框架的時候,只須要把這個框架依賴的日誌框架排除掉便可;

四、日誌使用

一、默認配置

SpringBoot默認幫咱們配置好了日誌;

@Test
public void contextLoads() {
   //日誌記錄器
   Logger logger = LoggerFactory.getLogger(getClass());
   //日誌的級別
   //由低到高 trace<debug<info<warn<error
   //能夠調整輸出的日誌級別,日誌就只會在這個級別及之後的高級別生效
   logger.trace("這是trace日誌...");
   logger.debug("這是dubug日誌...");
   //SpringBoot默認給咱們使用的是info級別的,沒有指定級別就用SpringBoot默認規定的級別:root級別
   logger.info("這是info日誌。。。");
   logger.warn("這是warn日誌。。。");
   logger.error("這是error日誌。。。");

}

 

<pattern>%d{yyyy-MM-dd HH:mm:ss} %p%M-> %m%n</pattern>

以上格式說明以下:

 

%M 輸出代碼中指定的消息
%p 輸出優先級,即DEBUG,INFO,WARN,ERROR,FATAL
%r 輸出自應用啓動到輸出該log信息耗費的毫秒數
%c 輸出所屬的類目,一般就是所在類的全名
%t 輸出產生該日誌事件的線程名
%n 輸出一個回車換行符,Windows平臺爲「\r\n」,Unix平臺爲「\n」
%d 輸出日誌時間點的日期或時間,默認格式爲ISO8601,也能夠在其後指定格式,好比:%d{yyy MMM dd HH:mm:ss,SSS}, 輸出相似:2002年10月18日 22:10:28,921
%l 輸出日誌事件的發生位置,包括類目名、發生的線程,以及在代碼中的行數。舉例:Testlog4.main(TestLog4.java:10)

SpringBoot 修改日誌的默認配置

logging.level.org.wl= trace

#logging.file=D:springboot.log
#當前磁盤的根路徑下建立spring文件夾和裏面的log文件夾;使用spring.log做爲默認文件
#logging.path=/spring/log
#指定文件中日誌的輸出格式
logging.pattern.console=

 

==logback依賴==

<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId> <version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-access</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>

二、指定配置

給路徑下放在每個日誌框架本身的配置文件便可;SpringBoot 就不使用其餘默認配置了

LOGGING SYSTEM CUSTOMIZATION
Logback logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2 log4j2-spring.xml or log4j2.xml

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

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

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

不然

no applicable active for [springProfile]

 

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
   <!--encoder 默認配置爲PatternLayoutEncoder-->
   <encoder>
       <springProfile name="dev">
           <pattern>===>>>>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
           <charset>utf-8</charset>
       </springProfile>
       <springProfile name="!dev">
           <pattern>===>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
           <charset>utf-8</charset>
       </springProfile>
   </encoder>
   <!--此日誌appender是爲開發使用,只配置最底級別,控制檯輸出的日誌級別是大於或等於此級別的日誌信息-->
   <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
       <level>debug</level>
   </filter>
</appender>

五、切換日誌框架

能夠按照Slf4J日誌適配圖,進行相關的切換;

slf4+log4的方式

 

切換成爲log4J2

 

4、Web開發

一、簡介

使用SpringBoot;

1)、建立SpringBoot應用,選中咱們須要的模塊;

2)、SpringBoot已經默認將這些場景配置好了?只須要在配置文件中指定少許配置就能夠運行起來;

3)、本身編寫業務代碼;

自動配置原理?

這個場景SpringBoot幫咱們配置好了什麼?能不能修改?能修改哪些配置?能不能擴展?xxx

xxxx.AutoConfiguration:幫咱們給容器中自動配置組件
xxxx.Properties:配置類來封裝配置文件的內容

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

private Integer getSeconds(Duration cachePeriod) {
  return (cachePeriod != null) ? (int) cachePeriod.getSeconds() : null;
}

==1)、全部/webjars/**,都去classpath:/META-INF/resources/webjars/找資源;==

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

https://www.webjars.org/

 

localhost:8081/webjars/jquery/3.3.1-1\jquery.js

<!-- 引入jquery-webjars-->在訪問的時候只須要寫webjars下面的內容便可
<dependency>
   <groupId>org.webjars</groupId>
   <artifactId>jquery</artifactId>
   <version>3.3.1-1</version>
</dependency>

==2 、**"訪問當前項目的任何資源,(靜態資源的文件夾==)

"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/"當前項目的根路徑

localhost:8081/abc === 去靜態資源文件夾裏面找abc

==3) 、迎頁:靜態資源文件夾下的全部index.html頁面;被「/**」映射;==

localhost:8080/找index頁面

//配置歡迎頁映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(
     ApplicationContext applicationContext) {
  return new WelcomePageHandlerMapping(
        new TemplateAvailabilityProviders(applicationContext),
        applicationContext, getWelcomePage(),
        this.mvcProperties.getStaticPathPattern());
}

==4)、全部的**/favicon.ico都是在靜態資源文件下找==

//配置咱們喜歡的圖標
@Configuration
  @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
  public static class FaviconConfiguration implements ResourceLoaderAware {

     private final ResourceProperties resourceProperties;

     private ResourceLoader resourceLoader;

     public FaviconConfiguration(ResourceProperties resourceProperties) {
        this.resourceProperties = resourceProperties;
    }

     @Override
     public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

     @Bean
     public SimpleUrlHandlerMapping faviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
//全部 **/favicon.ico         mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
              faviconRequestHandler()));
        return mapping;
    }

     @Bean
     public ResourceHttpRequestHandler faviconRequestHandler() {
        ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
        requestHandler.setLocations(resolveFaviconLocations());
        return requestHandler;
    }

     private List<Resource> resolveFaviconLocations() {
        String[] staticLocations = getResourceLocations(
              this.resourceProperties.getStaticLocations());
        List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
        Arrays.stream(staticLocations).map(this.resourceLoader::getResource)
              .forEach(locations::add);
        locations.add(new ClassPathResource("/"));
        return Collections.unmodifiableList(locations);
    }

  }

}

三、模板引擎

JSP、Velocity、Freemarker、Thymeleaf;

 

 

SpringBoot推薦的Thymeleaf;

語法更簡單、功能更強大;

一、引入thymeleaf;

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

 

二、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";
//只要我麼把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染;

使用:

一、導入thymeleaf的名稱空間

<html lang="en" xmlns:th="http://www.thymeleaf.org">

二、使用thymeleaf的語法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
   <meta charset="UTF-8">
   <title>成功</title>
</head>
<body>
   <h1>成功</h1>
   <!--th:text將div裏面的文本內容設置爲-->
   <div th:text="${hello}">這是顯示歡迎信息</div>
</body>
</html>

三、語法規則

1)、th:text;改變當前元素裏面的文本內容;

th:任意html屬性;來替換原生屬性的值

 

2)、表達式?

Simple expressions:(表達式語法)
  Variable Expressions: ${...}獲取變量的值OGNL;
  1)、獲取對象的屬性、調用方法;
  2)、使用內置的基本對象;
  #ctx : the context object.
#vars: the context variables.
      #locale : the context locale.
      #request : (only in Web Contexts) the HttpServletRequest object.
      #response : (only in Web Contexts) the HttpServletResponse object.
      #session : (only in Web Contexts) the HttpSession object.
      #servletContext : (only in Web Contexts) the ServletContext object.
      3)、內置的一些工具對象
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they
would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
Page 20 of 106
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
   
  Selection Variable Expressions: *{...}選擇表達式;和${}在功能上是同樣;
  補充;配合 th:object="${session.user}"
  <div th:object="${session.user}">
<p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
<p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
<p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>

</div>
  Message Expressions: #{...}獲取國際化功能的
   
  Link URL Expressions: @{...}定義URL
  @{/order/process(execId=${execId},execType='FAST')}
   
  Fragment Expressions: ~{...}片斷引用的表達式
  <div th:insert="~{commons :: main}">...</div>
   
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: _

四、SpringMVC自動配置

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

一、 Spring MVC Auto-configuration

SpringBoot自動配置好了SpringMVC

如下是SpringBoot對SpringMVC的默認:

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

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

    • ContentNegotiatingViewResolver組合了全部視圖解析器的;

    • ==如何定製:咱們能夠本身給容器中添加一個視圖解析器;自動的將其組合進來;==

  • Support for serving static resources, including support for WebJars (covered later in this document)).靜態資源文件夾路徑webjars

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

  • Custom Favicon support (covered later in this document).

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

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

    • Formatter:格式化器;2018.10.7====date

      @Bean
     @ConditionalOnMissingBean
     @ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
     public LocaleResolver localeResolver() {
        if (this.mvcProperties
              .getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
           return new FixedLocaleResolver(this.mvcProperties.getLocale());
        }
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
        return localeResolver;
    }

    ==本身添加的格式化轉化器,咱們只須要放在容器中便可==

  • Support for HttpMessageConverters (covered later in this document).

    • HttpMessageConverters:SpringMVC用來轉換Http請求和響應的;user---json;

    • HttpMessageConverters是從容器中肯定;獲取全部的`HttpMessageConverters;

      ==本身給容器中添加HttpMessageConverter,只須要將本身的組件註冊容器中(@Bean,@Component)==

  • Automatic registration of MessageCodesResolver (covered later in this document).

    定義錯誤代碼生成規則

  • Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).

    ==咱們能夠配置一個ConfigurableWebBindingInitializer來替換默認的(添加到容器中);==

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

==org.springframework.boot.autoconfigure.web:web的全部自動場景==

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

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

二、擴展SpringMVC

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

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

==WebMvcConfigurerAdapter過時,使用新的WebMvcConfigurationSupport==

既保留了全部的自動配置,也能用咱們的擴展配置;

//使用WebMvcConfigurationSupport能夠擴展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport {

   protected void addViewControllers(ViewControllerRegistry registry) {
       //瀏覽器發送/wl請求來到success
       registry.addViewController("/wl").setViewName("success");

  }

}

原理:

1)、WebMvcAutoConfiguration是SpringMVC自動配置類

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

@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {


//從容器中獲取全部的WebMvcConfiguration
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}//一個參考實現;將全部的WebMvcConfigurer相關配置都一塊兒調用
}

3)、容器中全部的WebMvcConfiguration 都會一塊兒起做用

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

效果:SpringMvc 的自動配置和咱們的擴展配置都會起做用;

3 、全面接管SpringMVC

springBoot對springmvc的自動配置不須要了,全部都是咱們本身配;全部的SpringMvc的自動配置都失效;咱們須要在配置類中添加@EnableWebMvc便可

 

 

 

 

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

模式:

1)、SpringBoot再自動配置不少組件的時候,先看容器 中有沒有用戶本身配置的(@Bean、@Component)若是有就用用戶配置的,若是沒有,才自動配置;若是有些組件能夠有多個(ViewResolver)將用戶配置的和他本身默認的組合起來;

2)、在SpringBoot中會有很是多的xxxConfigurer幫助咱們進行擴展配置;

相關文章
相關標籤/搜索