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 SystemCustomization
Logbacklogback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2log4j2-spring.xml or log4j2.xml
JDK (Java Util Logging)logging.properties

logback.xml直接被日志框架识别

logback-spring.xml日志框架就不自己加载,由springboot加载, 由springboot解析日志配置文件,可以使用profile高级功能

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

<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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以和你分享一些关于Spring Boot的学习笔记。 1. Spring Boot是什么? Spring Boot是一个基于Spring框架的快速开发框架,它能够帮助开发者快速搭建Spring项目,简化了Spring应用开发的繁琐过程,提高了开发效率。 2. Spring Boot的优点有哪些? Spring Boot的优点有很多,其中包括: - 简化了Spring应用的开发,提高了开发效率; - 集成了很多常用的第三方库,减少了依赖管理的工作; - 自动配置,减少了配置文件的编写工作; - 内嵌了Tomcat等Web容器,使得应用的部署更加便捷; - 提供了Actuator等模块,使得应用的监控和管理更加便捷。 3. Spring Boot的核心注解有哪些? Spring Boot的核心注解包括: - @SpringBootApplication:标注在启动类上,代表这是一个Spring Boot应用; - @Controller:标注在控制器类上,处理HTTP请求; - @Service:标注在服务类上,用于处理业务逻辑; - @Repository:标注在数据访问类上,用于数据库访问; - @Configuration:标注在配置类上,用于配置Spring应用上下文。 4. Spring Boot的配置文件有哪些? Spring Boot的配置文件包括: - application.properties:基于Key-Value的属性文件; - application.yml:基于YAML语法的配置文件。 5. 如何使用Spring Boot集成数据库? 使用Spring Boot集成数据库需要完成以下几个步骤: - 在pom.xml中添加相关数据库依赖; - 配置数据源和JPA/Hibernate等相关配置; - 编写实体类和DAO层代码。 以上就是一些关于Spring Boot的学习笔记,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值