SpringBoot文档

时间:2022-09-25 09:31:58

一、Spring Boot 入门

1、Hello World探究

1、POM文件

1、父项目

<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 版本仲裁中心:

以后我们导入依赖默认是不需要写版本:(没有在dependencies里面管理的依赖自然需要写版本号)

2、启动器

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

spring-boot-starter-web: Spring Boot 场景启动器帮我们导入了Web模块正常运行所依赖的组件;

Spring Boot 将所有相关场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starters相关场景的所有依赖都会导入进来。要用什么功能就导入什么场景的启动器

2、主程序类、注入口类

/*
* @SpringBootApplication 来标注一个主程序类,说明这是一个Spring Boot 应用
*/
@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
      //spring应用启动起来
     SpringApplication.run(DemoApplication.class, args);
  }
}

@SpringBootApplication :Spring Boot 应用标注在某个类上说明这个类是SpringBoot的主配置类,

SpringBoot就应该运行这个类的main方法来启动SpringBoot应用;

@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 的配置类;

标注在某个类上,表示这是一个Spring Boot 的配置类;

@Configuration:配置类上来标注这个注解;

配置类-------配置文件:配置类也是容器中的一个组件;@Component

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

2、使用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 应用的配置文件;可以修改一些默认配置;

二、 配置文件

1、配置文件

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>

2、YAML语法

1、基本语法

k:(空格)v:表示一对键值对(空格必须有);

以空格缩进来控制层级关系:只要是左对齐的一列数据,都是一个层级的

server:
port: 8090
path: /hello

属性和值也是大小写敏感的;

2、值的写法

字面量:普通的值(数学,字符串,布尔)

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}

3、配置文件值注入

配置文件

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>

1、properties配置文件在idea中默认UTF-8可能会乱码

2、@value获取值和@ConfigurationProperties获取值比较

  @CONFIGURATIONPROPERTIES @VALUE
功能 批量注入配置文件中的属性 一个一个指定
松散绑定(松散语法) 支持 不支持
SpEL(表达式计算) 不支持 支持
JSR303数据校验 支持 不支持
复杂类型封装 支持 不支持

配置文件yml还是properties他们都能获取到值;

如果说,我们只是在某和业务逻辑中需要获取一下配置文件的某项值,使用@Value

如果说我们专门编写了一个javabean来和配置文件进行映射,我们就直接使用@ConfigurationProperties;

3、配置文件注入值数据校验

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

4、@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 推荐给容器中添加组件的方式;

1、配置类=========Spring配置文件

2、使用@Bean给容器中添加组件

/*
* @Configuration:指明当前类是一个配置文件;就是来替代之前的Spring配置文件
*在配置文件中用<bean></bean>标签添加组件
*
* */

@Configuration
public class MyAppConfig {
   //将方法的返回值添加到容器中;容器中这个组件默认的id就是方法名
   @Bean
   public HelloService helloService(){
       System.out.println("配置类@bean给容器中添加组价了。。。");
       return new HelloService();
  }
}

4、配置文件占位符

1、随机数

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

2、占位符获取之前配置的值,如果没有可以是用:指定默认值

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

5、Profile

1、多Profile文件

我们在主配置文件编写的时候,文件名可以是application-{profile}.properties/yml

默认使用application.properties的配置;

2、yml支持多文档块方式

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

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

server:
port: 8004
spring:
profiles: prod

---

3、激活指定profile

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

2、命令行:

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

可以直接在测试的时候,配置传入命令行参数

3、 虚拟机参数:

-Dspring.profile.active=dev

6、配置文件加载位置

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

7、外部配置加载顺序

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指定的默认属性

    所有的配置加载来源;

    参考官方文档

8、自动配置原理

配置文件到底能写什么?怎么写?自动配置原理;

配置文件能配置的属性参照

1、自动配置原理

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:封装配置文件中的相关属性;

2、细节

1、@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)

三、日志

1、日志框架

小张:开发一个大型系统:

1、System.out.println("");将关键数据打印在控制台:去掉?写在一个文件?

2、框架来记录系统的一些运行时信息;日志框架;zhanglogging.jar;

3、高大上的几个功能?异步模式?自动归档?xxxx?zhanglogging-good.jar?

4、将以前框架卸下来?换上了新的框架,重新修改之前相关的API;zhanglogging-prefect.jar;

5、JDBC---数据库驱动;

写了一个统一的接口层;日志门面(日志的一个抽象层);logging-abstract.jar;

给项目中导入具体的日志实现就行了;我们之前的日志框架都是实现的抽象层;

市面上的日志框架;

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

左面选一个门面(抽象层)、右边来选一个实现;

日志门面:SLF4J;

日志实现:Logback;

SpringBoot:底层框架Spring框架,Spring框架默认是用JCL;

SpringBoot 选用SLF4J和logback;

2、SLF4J使用

1、如何在系统中使用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");
}
}

图示:SpringBoot文档

每一个日志的实现框架都有自己的配置文件,使用slf4j以后,配置文件还是做成日志实现框架自己本身的配置文件

2、遗留问题

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

统一日志记录,即使是别的框架和我们一起统一使用slf4j进行输出?

SpringBoot文档

如何让系统中所有的日志都统一到Slf4j;

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

==2、用中间包来替换原有的日志框架;==

==3、我们导入slf4其他的实现==

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>
 <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的记录方式记录日志,引入其他框架的时候,只需要把这个框架依赖的日志框架排除掉即可;

4、日志使用

1、默认配置

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>

2、指定配置

给路径下放在每一个日志框架自己的配置文件即可;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>

5、切换日志框架

可以按照Slf4J日志适配图,进行相关的切换;

slf4+log4的方式

切换成为log4J2

四、Web开发

1、简介

使用SpringBoot;

1)、创建SpringBoot应用,选中我们需要的模块;

2)、SpringBoot已经默认将这些场景配置好了?只需要在配置文件中指定少量配置就可以运行起来;

3)、自己编写业务代码;

自动配置原理?

这个场景SpringBoot帮我们配置好了什么?能不能修改?能修改哪些配置?能不能扩展?xxx

xxxx.AutoConfiguration:帮我们给容器中自动配置组件
xxxx.Properties:配置类来封装配置文件的内容

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

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

  }

}

3、模板引擎

JSP、Velocity、Freemarker、Thymeleaf;

SpringBoot推荐的Thymeleaf;

语法更简单、功能更强大;

1、引入thymeleaf;

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

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";
//只要我么把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

使用:

1、导入thymeleaf的名称空间

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

2、使用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>

3、语法规则

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: _

4、SpringMVC自动配置

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

1、 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.

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),是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即可

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

模式:

1)、SpringBoot再自动配置很多组件的时候,先看容器 中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和他自己默认的组合起来;

2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置;

SpringBoot文档的更多相关文章

  1. springBoot文档地址

    文档: https://www.gitbook.com/book/qbgbook/spring-boot-reference-guide-zh/details 配置: http://docs.spri ...

  2. 基于springboot的freemarker创建指定格式的word文档

    在web或其他应用中,经常我们需要导出或者预览word文档,比较实际的例子有招聘网站上预览或者导出个人简历,使用POI导出excel会非常的方便,但是如果想导出word,由于其格式控制非常复杂,故而使 ...

  3. SpringBoot整合Swagger2,再也不用维护接口文档了!

    前后端分离后,维护接口文档基本上是必不可少的工作.一个理想的状态是设计好后,接口文档发给前端和后端,大伙按照既定的规则各自开发,开发好了对接上了就可以上线了.当然这是一种非常理想的状态,实际开发中却很 ...

  4. springboot~mockMvc和asciidoctor生成基于TDD的API文档

    API文档是前端与后端快速开发,减少沟通成本的必要条件,有一份完善的文档是很必要的,由通过测试来生成文档的好处就是:测试数据有了,测试返回结果有了,而且可以对这些字段进行说明,很清晰,在springb ...

  5. SpringBoot入门教程&lpar;二十&rpar;Swagger2-自动生成RESTful规范API文档

    Swagger2 方式,一定会让你有不一样的开发体验:功能丰富 :支持多种注解,自动生成接口文档界面,支持在界面测试API接口功能:及时更新 :开发过程中花一点写注释的时间,就可以及时的更新API文档 ...

  6. springboot项目利用Swagger2生成在线接口文档

    Swagger简介. Swagger2是一款restful接口文档在线生成和在线调试工具.很多项目团队利用Swagger自动生成接口文档,保证接口文档和代码同步更新.在线调试.简单地说,你可以利用这个 ...

  7. SpringBoot系列&colon; 使用 Swagger 生成 API 文档

    SpringBoot非常适合开发 Restful API程序, 我们都知道为API文档非常重要, 但要维护好难度也很大, 原因有: 1. API文档如何能被方便地找到? 以文件的形式编写API文档都有 ...

  8. springboot&plus;mybatis-puls利用swagger构建api文档

    项目开发常采用前后端分离的方式.前后端通过API进行交互,在Swagger UI中,前后端人员能够直观预览并且测试API,方便前后端人员同步开发. 在SpringBoot中集成swagger,步骤如下 ...

  9. SpringBoot整合Swagger2搭建API在线文档

    Swagger,中文"拽"的意思,它是一个功能强大的在线API在线文档,目前它的版本为2.x,所以称为Swagger2.Swagger2提供了在线文档的查阅和测试功能.利用Swag ...

随机推荐

  1. H3 BPM初次安装常见错误详解1-4

    错误1: 首次安装完成无法访问,效果如下. 错误原因:没有配置IIS. 解决方法: 控制面板-程序-打开或关闭Windows功能,选择internet信息服务. 因为安装的时候没有没有iis,所以程序 ...

  2. JavaScript弹窗

    警告框: alert("警告信息!"); alert("警告\n信息!"); 确认框: var t=confirm("请确认!"); // ...

  3. 字符串处理:ABAP中的正则表达式

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  4. hibernate一对一双向外键关联

    一对一双向外键关联:双方都持有对方的外键关联关系. 主控方和一对一单向外键关联的情况是一样的,主要的差异表现为,被空方需要添加: @OneToOne(mappedBy="card" ...

  5. Spring源码入门——XmlBeanDefinitionReader解析

    接上篇[] ,我们看到BeanDefinitionReader解决的是从资源文件(xml,propert)到BeanDefinition集合的过程.所以BeanDefinitionReader接口有两 ...

  6. bzoj1009

    设f[i,j]为准考证号上第i位匹配到不吉祥数字第j位的方案数,显然j∈[0,m-1]下面我们就要想到怎么把f[i-1]转移到f[i]也就是当前匹配到第k位,那么下一位可能会匹配到哪一位显然我们可以穷 ...

  7. 转:【Java集合源码剖析】Java集合框架

    转载轻注明出处:http://blog.csdn.net/ns_code/article/details/35564663   Java集合工具包位于Java.util包下,包含了很多常用的数据结构, ...

  8. R︱foreach&plus;doParallel并行&plus;联用迭代器优化内存&plus;并行机器学习算法

    要学的东西太多,无笔记不能学~~ 欢迎关注公众号,一起分享学习笔记,记录每一颗"贝壳"~ --------------------------- 接着之前写的并行算法paralle ...

  9. 对ajax基础的掌握随笔

    原始的ajax,在第一个页面定义如下: function createAjax() { var xmlhttp; if (window.ActiveXObject) xmlhttp = new Act ...

  10. hdu多校第3场A&period;Ascending Rating

    Problem A. Ascending Rating Time Limit: / MS (Java/Others) Memory Limit: / K (Java/Others) Total Sub ...