SpringBoot2核心技术

文章目录


学习目标

熟悉使用SpringBoot进行快速构建并开发项目。

一、SpringBoot2核心技术,基础入门

学习要求: 熟悉Spring基础、熟悉Maven使用
环境要求: Java8及以上、Maven3.3及以上

1、Spring与SpringBoot

1.1、Spring可以做什么

图片来源于Spring官网:Spirng官网
在这里插入图片描述
译后对应为:
在这里插入图片描述

1.2 、Sping的生态

  1. web开发
  2. 数据访问
  3. 安全控制
  4. 分布式
  5. 消息服务
  6. 移动开发
  7. 批处理
    等等

2、为什么要学习使用SpringBoot

1、Spirng的优点

SpringBoot是整合Spring技术栈的一站式框架
SpingBoot是简化Spring技术栈的快速开发平台

  1. 能够创建独立的Sping应用;
  2. 内嵌web服务器;
  3. 自动化依赖,简化项目构建的配置;
  4. 自动Sping以及第三方的功能;
  5. 提供生产级别的监控、健康检查以及外部化的配置;
  6. 无代码生成、没有xml的编写步骤。

2、Spirng的缺点

  1. 迭代快;
  2. 封装的比较深,原理比较复杂,不太容易精通

3、背景

3.1、微服务(2014年提出)
  1. 微服务是一种架构的风格;
  2. 一个应用拆分成一组小型服务;
  3. 每个服务运行在自己的进程内,意味着可以独立部署和开发升级;
  4. 服务之间使用轻量级的HTTP进行交互;
  5. 服务围绕业务功能进行拆分;
  6. 可以由全自动部署机制独立部署;
  7. 去中心化,服务自治。服务可以用用不同的语言、不同的存储技术
3.2、分布式

①分布式的困难

  1. 远程调用
  2. 服务发现
  3. 负载均衡
  4. 服务容错
  5. 配置管理
  6. 服务监控
  7. 链路追踪
  8. 日志管理
  9. 任务调度

②分布式的解决
SpirngBoot+SpringCloud
在这里插入图片描述

3.2 云原生(有点空洞暂时不做了解)

3、SpringBoot入门

3.1、系统要求

  1. Java8及以上
  2. maven3.3

3.2、maven设置

开始之前我们看一下本地的系统环境
在这里插入图片描述
打开我们的maven安装目录:D:\tools\apache-maven-3.6.3\conf修改settings.xml文件,把以下代码粘贴到settings.xml文件中,如果你的配置文件中已经出现如下代码,则不需要再次添加:

<!-- 此处为阿里云镜像-->
<mirrors>
      <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
      </mirror>
  </mirrors>
 <!-- 此处为告诉我们的maven用哪个版本的jdk进行编译-->
  <profiles>
         <profile>
              <id>jdk-1.8</id>
              <activation>
                <activeByDefault>true</activeByDefault>
                <jdk>1.8</jdk>
              </activation>
              <properties>
                <maven.compiler.source>1.8</maven.compiler.source>
                <maven.compiler.target>1.8</maven.compiler.target>
                <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
              </properties>
         </profile>
  </profiles>

3.3、HelloWorld

要求:浏览器发送一个请求,响应一个HelloWorld字符串

3.3.1、创建Maven工程

在这里插入图片描述

3.3.2、引入依赖
	
	<!--此处为一个父工程,说明我们的项目为SpringBoot项目-->
	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
    </parent>

	<!--此处为web开发场景依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

在这里插入图片描述
依赖加载完成之后,在这里插入图片描述

3.3.3、创建主程序
package com.wyq.boot;

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

/**
 * @author wyq
 * 此类也叫做主程序类,也就是左右程序的启动入口
 * 告诉SpringBoot这是一个SpingBoot的应用
 *
 */
@SpringBootApplication
public class MainApplication {
	public static void main(String[] args) {
		SpringApplication.run(MainApplication.class,args);
	}
	
	
}

3.3.4、编写业务
package com.wyq.boot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wyq
 * @RequestMapping 映射请求
 * @ResponseBody 返回值
 * @RestController SpirngMvc的轻注解,可以省略@RequestMapping、@ResponseBody
 *
 */
@RestController
//@Controller
public class HelloController {
	//@ResponseBody
	@RequestMapping("/hello")
	public String hello() {
		return "hello 我是第一次学习SpringBoot哦";
	}
}

3.3.5、测试

运行 MainApplication 类下的main方法
在这里插入图片描述
控制台打印此这些日志,说tomcat已经在8080端口下边启动了。
接下来我们打开浏览器进行访问测试:
在这里插入图片描述

3.3.6、简化配置
application.properties

以修改端口号为例
resources下新建此文件:
在这里插入图片描述
在此文件中写入server.port=8888 代码,重新启动项目发现端口已经更改,如下图所示:
在这里插入图片描述
此时在浏览器在此用8080端口访问,发现已经不能访问在这里插入图片描述

把地址该为8888后再次访问:在这里插入图片描述

3.3.7、简化部署

在xml文件中加入如下代码:

 <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

把项目打成jar包,在目标服务器执行即可。

打包过程:①项目右键选择【Run As】 点击【Maven clean】,执行此过程可能会报错,原因可能是在2.2中的maven设置中配置settings文件出错。
注意:无论咋settings中添加什么样的配置profiles 标签只能有一个开头和结束。
在这里插入图片描述
②项目右键选择【Run As】 点击【Maven install】
在这里插入图片描述
③打开项目路径中的target文件夹,我们的jar包就是生成到了这个文件夹下,然后我们来用命令的方式进行启动项目并访问
在这里插入图片描述
④输入命令:java -jar study_boot-0.0.1-SNAPSHOT.jar,回车
在这里插入图片描述
项目启动完成。
⑤我们来进行访问,记得把eclipse中的项目要停掉
在这里插入图片描述
注意事项:1、一定要取消掉cmd的快速编辑模式在这里插入图片描述

4、了解自动配置的原理

4.1、SpringBoot特点

4.1.1、依赖管理
  1. 依赖管理
    pom文件中引入的父项目来做依赖管理:
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
    </parent>

此时我们进入到这个父项目中发现,它还有一个父项:

 <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.3.4.RELEASE</version>
  </parent>

然后在进入spring-boot-dependencies这个里边我们仔细看会发现,这父项基本声明了所有开发中常用的版本号,这就是自动版本仲裁机制:
在这里插入图片描述

  1. 开发导入starter场景启动项器:
    所有我们pom文件中见到的类似于spring-boot-starter-* 都是我们引入的场景,并且所有的依赖我们都会自动引入。例web开发
<dependency>
   	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

而它的底层是:

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

因为SpringBoot提供了自定义启动器,所有以后我们见后的*-spring-boot-starter 这都是第三方提供给我们的简化开发启动器

  1. 不需要关注版本号,自动版本仲裁:
    引入依赖无需填写版本号
    引入非SpringBoot的依赖需要写入版本号
  2. 修改版本号:在当前项目中的pom文件中重写
    mysql的maven仓库
 <properties>
    <mysql.version>5.7.29</mysql.version>
 </properties>
4.1.2、自动配置
  1. 自动配置好tomcat
    引入tomcat依赖
    我们点入到在这里插入图片描述 这里就可以看到:
<dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-annotations-api</artifactId>
        <version>${tomcat.version}</version>
      </dependency>

配置tomcat

  1. 自动配置好了SpringMVC
    引入了SpringMVC的全部组件
    自动配置好了SpringMVC的常用组件
  2. 自动配置好了web开发的常用场景,比如字符乱码等等
    SpringBoot帮我们配置好了常用的web开发的场景
  3. 默认的包结构
    主程序所在的包以及子包的所有组件都可以被默认扫描
    不需要配置包扫描
    如果想要改变扫描路径,启动项配置@SpringBootApplication(scanBasePackages="com.wyq")
    或者使用@ComponentScan("com.wyq")
    次数要注意:SpringBootApplicationComponentScan不能同时使用
@SpringBootApplication
等同于
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.wyq.boot")
  1. 各种配置都有默认值
    各种配置始终都是映射到了某个类上
    配置文件最终会绑定到每个类上,这个类会在容器中创建对象
  2. 按需要加载所有的自动配置项
    有很多的starter
    引入了哪些场景这个场景的自动配置才会开启
    SpringBoot所有的自动配置都在spring-boot-autoconfigure中,
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-autoconfigure</artifactId>
      <version>2.3.4.RELEASE</version>
      <scope>compile</scope>
</dependency>

4.2、容器功能

4.2.1、组件添加
1、@Configuration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.wyq.boot.bean.User;

/**
 * 1.配置类使用@bean标注在方法上给容器注册组件,默认是单实例的
 * 2.配置类本身也是组件
 * 3.proxyBeanMethods:代理bean的方法
 * 	 Full(proxyBeanMethods = true)、【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
 *   Lite(proxyBeanMethods = false)【每个@Bean方法被调用多少次返回的组件都是新创建的】
 *      组件依赖必须使用Full模式默认。其他默认是否Lite模式
 * 
 * @author wyq
 *
 */
@Configuration(proxyBeanMethods = false) // 这是一个配置类,等同于配置文件
public class MyConfig {
	
	/**
	 * 外部无论对配置类中的这个组件注册方法调用多少次都是得到之前注册
	 * 
	 * @return
	 */
	@Bean // 给容器中添加组件,以方法名作为组件的ID,返回类型就是组件的类型,返回值就是组件在容器中的单实例对象
	public User user01() {
		return new User("xiaose", 14);
	}
}
2、@controller、@bean、@Service、@Component、@Repository
3、@ComponentScan、@Import
/**
*给容器中自动创建出User这两个类型的组件,默认组件就是全类名
*/
@Import({User.class})
@Configuration(proxyBeanMethods = false) // 这是一个配置类,等同于配置文件
public class MyConfig {
}
4、@Conditional
4.2.2、原生配置文件引入
1、@ImportResoure 导入资源
@ImportResource("classpath:****.xml")
public class MyConfig {}
4.2.3、配置绑定
1、@ConfigurationProperties(prefix=“myproperties”)+@EnableConfigurationProperties(PropertiesBean.class)

// 开启属性配置功能,把PropertiesBean组件自动注入到容器中

2、@Component+@ConfigurationProperties(prefix=“myproperties”)
package com.wyq.boot.bean;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 只有在容器中的功能,才能拥有SpringBoot提供的强大功能
 * @author zhixing-js
 *
 */
@Component // 加入到容器中
@ConfigurationProperties(prefix="myproperties")
public class PropertiesBean {
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "PropertiesBean [name=" + name + ", age=" + age + "]";
	}
}

4.3、自动配置原理入门

4.3.1、引导加载自动配置类

@SpringBootApplication 是下边这一堆注解的合成

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {}
  1. @SpringBootConfiguration
    @Configuration 代表当前是一个配置类
  2. @ComponentScan 指定我们要扫描哪些
  3. @EnableAutoConfiguration
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}

①@AutoConfigurationPackage

@Import(AutoConfigurationPackages.Registrar.class)// 给容器中导入一个组件
public @interface AutoConfigurationPackage {}
// 给容器中导入一系列的组件
// 将指定的一个(MainApplication)所在包下的所有组件导入进来

②@Import(AutoConfigurationImportSelector.class)
1>利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入组件
2>调用List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取到所有需要导入到容器中的配置类
3>利用工厂Map<String, List> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
4>从META-INF/spring.factories位置来加载一个文件。
默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories

在这里插入图片描述
文件里面写死了spring-boot一启动就要给容器中加载的所有配置类
spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories

# Initializers
org.springframework.context.ApplicationContextInitializer=\
org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\
org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.autoconfigure.BackgroundPreinitializer

# Auto Configuration Import Listeners
org.springframework.boot.autoconfigure.AutoConfigurationImportListener=\
org.springframework.boot.autoconfigure.condition.ConditionEvaluationReportAutoConfigurationImportListener

# Auto Configuration Import Filters
org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\
org.springframework.boot.autoconfigure.condition.OnBeanCondition,\
org.springframework.boot.autoconfigure.condition.OnClassCondition,\
org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition

# 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.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
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.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
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.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
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.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
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.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
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.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
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.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
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.ClientHttpConnectorAutoConfiguration,\
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,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

# Failure analyzers
org.springframework.boot.diagnostics.FailureAnalyzer=\
org.springframework.boot.autoconfigure.data.redis.RedisUrlSyntaxFailureAnalyzer,\
org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\
org.springframework.boot.autoconfigure.flyway.FlywayMigrationScriptMissingFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\
org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer,\
org.springframework.boot.autoconfigure.r2dbc.ConnectionFactoryBeanCreationFailureAnalyzer,\
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

4.3.2、按需开启自动配置项

自动配置启动的时候会默认全部加载,******-autoconfigure,但是按照条件装配规则(@Conditional),最终会按需配置。

4.3.3、修改默认配置
@Bean
@ConditionalOnBean(MultipartResolver.class)// 容器中有这个类型的组件
@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) // 容器中没有这个名字multipartResolver的组件
public MultipartResolver multipartResolver(MultipartResolver resolver) {
	// 给@bean标注的方法传入对象参数,这个参数的值就会从容器中找
	// SpringMvc multipartResolver,防止用户配置的文件上传解析器不符合规范

	// Detect if the user has created a MultipartResolver but named it incorrectly
	return resolver;
}
// 给容器中加入了文件上传解析器。

SpringBoot会在底层默认配置好所有的组件,如果用户自己配置了,以用户配置的优先

@Bean
	@ConditionalOnMissingBean
	public CharacterEncodingFilter characterEncodingFilter() {
		CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
		filter.setEncoding(this.properties.getCharset().name());
		filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
		filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
		return filter;
	}

总结:

  1. SpringBoot先加载所有的自动配置类,比如*****AutoConfiguration;
  2. 每个自动配置类按照条件进行生效,都会默认绑定配置文件制定的值都从AutoConfiguration配置来,而AutoConfiguration又是和****Properties配置文件进行绑定;
  3. 如果生效,生效的配置类就会给容器中装配很多的组件;
  4. 只要容器中有这些组件,那就说明这些功能都可以使用了;
  5. 只要用户有自己配置的就以用户配置的优先;
  6. 定制化配置①用户直接自己@bean替换底层原生组件②用户去看这个组件获取的配置文件是什么值,去进行相应的修改位置在application.properties。

**所以至此,配置流程为:*****AutoConfiguration–>组件–>**Properties里进行取值–>application.properties

4.3.4、最佳实践
  1. 引入场景依赖;Spring官网配置场景依赖
  2. 查看自动配置了哪些东西,方法为在配置文件中写入debug=true开启自动配置报告。Negative(不生效)\Positive(生效);
  3. 是否需要修改①参照文档配置项官网配置项
    ②自定义加入或者替换组件:@bean、@Component。③自定义器***Customizer
    等等等等

4.4、开发小技巧

4.4.1、Lombok

简化javaBean开发

  1. 引入lombok插件
 <dependency>
		  	<groupId>org.projectlombok</groupId>
		   	<artifactId>lombok</artifactId>
		</dependency>
  1. 在IDE中安装lombok

简化javaBean的开发:

/**
 * 用户
 * @author wyq
 *
 */
@NoArgsConstructor  	// 无参构造器
//@AllArgsConstructor 	// 全参构造器
@Data					// get set方法
@ToString				// toString 方法
@EqualsAndHashCode		// 重写equals和HashCode方法	
public class User {
	private String name;
	private Integer age;
	
	public User(String name,Integer age) {
		this.name=name;
		this.age=age;
	}
}

简化日志的开发:

@Log4j2
@RestController
//@Controller
public class HelloController {
	@Autowired
	PropertiesBean propertiesBean;


	//@ResponseBody
	@RequestMapping("/hello")
	public String hello() {
		log.info("=========================");
		return "hello 我是第一次学习SpringBoot哦";
	}
	
	@RequestMapping("/propertiesBean")
	public PropertiesBean propertiesBean() {
		return propertiesBean;
	}
}

4.4.2、dev-tools

自动重启

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

在IDEA中是Ctrl+F9可进行直接更新,在eclipse中的话可直接保存项目就会自动重启

4.4.3、Spring Initailizr(项目初始化向导)

在Eclipse中

  1. 【File】–>【new】–>【Other】输入Spring在这里插入图片描述

  2. 点击【next】

  3. 输入我们的项目信息在这里插入图片描述

  4. 点击【next】,选择版本号,以及我们的各种需要的配置信息
    在这里插入图片描述

  5. 点击【Finish】
    在这里插入图片描述
    总结:

  6. 自动帮我们构建项目;

  7. 自动帮我们导入依赖;

  8. 自动编写好主配置类。

二、SpringBoot2核心技术,核心功能

在这里插入图片描述

1、配置文件

1.1、文件类型

1.1.1、properties

和之前的properties用法相同

1.1.2、yaml
1.1.2.1、简介

YAML 是 “YAML Ain’t Markup Language”(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:“Yet Another Markup Language”(仍是一种标记语言)。
非常适合用来做以数据为中心的配置文件

1.1.2.2、基本语法
  1. key: value;也是键值对的形式,但是中间有空格
  2. 大小写敏感
  3. 使用缩进的方式来表示层级结构关系
  4. 缩进不允许使用tab,只能使用空格,但是,缩进的空格数并不是很重要,只要是形同层级的元素左对其即可,所有我认为使用tab也是可以的;
  5. 表示注释

  6. 字符串不需要添加引号,如果要加,''与""表示字符串内容会被转义/不转义
1.1.2.3、数据类型
  1. 字面量:单个的、不可再分的值。date、boolean、string、number、null 例子:k: v
  2. 对象:键值对的集合。map、hash、set、object
    例:行内写法: k: [v1,v2,v3] 或者
k:
	- v1
	- v2
	- v3
  1. 数组:一组按照次序排列的值。array、list、queue
    例:行内写法: k: [v1,v2,v3] 或者
k:
	- v1
	- v2
	- v3
1.1.2.4、示例
package com.wyq.boot.bean;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import lombok.Data;
import lombok.ToString;

@ConfigurationProperties(prefix="person")
@Component
@ToString
@Data
public class Person {
	private String userName;
	private Boolean boss;
	private Date birth;
	private Integer age;
	private Pet pet;
	private String[] interests;
	private List<String> animal;
	private Map<String,Object> score;
	private Set<Double> salarys;
	private Map<String,List<Pet>> allPets;
	
}

package com.wyq.boot.bean;

import lombok.Data;
import lombok.ToString;

/**
 * 宠物
 * @author wyq
 *
 */
@ToString
@Data
public class Pet {
	private String name;
	private Double weigth;

	
}

person:
  userName: "李逵\n张飞"
  # 单引号回将\n作为字符串输出,双引号会将\n作为换行符输出
  #双引号不会转义,而单引号会转义
  
  boos: true
  birth: 2018/12/23
  age: 18
#interests: [篮球,羽毛球]
  interests: 
   - 篮球
   - 羽毛球
  animal: [猪头,狗头]
#  score: 
#    english: 80
#    math: 90 
  score: {english: 80,math: 90}
  salarys: 
    - 999
    - 4564.88
  pet: 
    name: 大黄
    weigth: 20
  allPets: 
    sick: 
      - {name: 小虎子,weigth: 23}
      - name: 小虎子2,
        weigth: 12
      - name: 小虎子
        weigth: 10
    health: 
      - {name: 健康宠物,weigth: 99}
      - {name: 健康宠物2,weigth: 100}

1.2、配置提示

为了让yml文件写的时候有提示

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-configuration-processor</artifactId>
     <optional>true</optional>
</dependency>

此处是为了打包的时候避开这个configuration配置

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                 <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

2、web开发

在这里插入图片描述

2.1、SpringMVC自动配置概览

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.
○ 内容协商视图解析器和BeanName视图解析器
● Support for serving static resources, including support for WebJars (covered later in this document)).
○ 静态资源(包括webjars)
● Automatic registration of Converter, GenericConverter, and Formatter beans.
○ 自动注册 Converter,GenericConverter,Formatter
● Support for HttpMessageConverters (covered later in this document).
○ 支持 HttpMessageConverters (后来我们配合内容协商理解原理)
● Automatic registration of MessageCodesResolver (covered later in this document).
○ 自动注册 MessageCodesResolver (国际化用)
● Static index.html support.
○ 静态index.html 页支持
● Custom Favicon support (covered later in this document).
○ 自定义 Favicon
● Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
○ 自动使用 ConfigurableWebBindingInitializer ,(DataBinder负责将请求数据绑定到JavaBean上)
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
不用@EnableWebMvc注解。使用 @Configuration + WebMvcConfigurer 自定义规则

If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
声明 WebMvcRegistrations 改变默认底层组件

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.
使用 @EnableWebMvc+@Configuration+DelegatingWebMvcConfiguration 全面接管SpringMVC

2.2、功能分析

2.2.1、静态资源访问

  1. 只要静态资源放在类路径下:static或者public或者resources或者META-INF/resources,例如:
    在这里插入图片描述

  2. 访问:当前项目的根路径/+资源的名字

  3. 原理:静态资源映射/**,请求进来,先去找Controller看可以处理不,不能处理的话就交给静态资源处理器,静态资源就去项目中去找,如过找不到,那就报404

  4. 可以改变默认的静态资源路径:

spring:
  mvc:
    static-path-pattern: /res/**

  resources:
    static-locations:
    - classpath:/haha/

2.2.2、静态资源访问前缀

默认没有前缀

spring:
  mvc:
    static-path-pattern: /res/**

当前项目+static-path-pattern+静态资源名=静态资源文件夹下找

2.2.3、webjar

自动映射 /webjars/**
webjars官网


        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.5.1</version>
        </dependency>

访问地址:http://localhost:8080/webjars/jquery/3.5.1/jquery.js 后面地址要按照依赖里面的包路径

2.2.2、欢迎页支持

  1. 静态资源下的index.html注意:可以配置静态资源路径,但是不可以配置静态资源的访问前缀
#spring:
#  mvc:
#    static-path-pattern: /res/** 这个会导致welcome page功能失效

  resources:
    static-locations:
    - classpath:/haha/

2.2.3、自定义Favicon

favicon.ico 放在静态资源目录下即可。

#spring:
#  mvc:
#    static-path-pattern: /res/** 会导致Favicon功能失效

2.2.4、静态资源配置原理

  1. SpringBoot启动默认加载XXXAutoConfiguration类(自动配置类)
  2. SpringMVC 的自动配置类集中在WebMvcAutoConfiguration
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {}
  1. 给容器中配了什么
@Configuration(proxyBeanMethods = false)
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {}
  1. 配置文件的相关属性跟什么进行了绑定:WebMvcProperties@ConfigurationProperties(prefix = "spring.mvc")绑定、ResourceProperties@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)绑定

  2. 一个配置类只有一个有参构造器


//有参构造器所有参数的值都会从容器中确定
//ResourceProperties resourceProperties;获取和spring.resources绑定的所有的值的对象
//WebMvcProperties mvcProperties 获取和spring.mvc绑定的所有的值的对象
//ListableBeanFactory beanFactory Spring的beanFactory
//HttpMessageConverters 找到所有的HttpMessageConverters
//ResourceHandlerRegistrationCustomizer 找到 资源处理器的自定义器。=========
//DispatcherServletPath  
//ServletRegistrationBean   给应用注册Servlet、Filter....

public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
				ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
				ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
				ObjectProvider<DispatcherServletPath> dispatcherServletPath,
				ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
			this.resourceProperties = resourceProperties;
			this.mvcProperties = mvcProperties;
			this.beanFactory = beanFactory;
			this.messageConvertersProvider = messageConvertersProvider;
			this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
			this.dispatcherServletPath = dispatcherServletPath;
			this.servletRegistrations = servletRegistrations;
		}
  1. 资源处理的默认规则
@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));
			}
		}
#spring:
#  mvc:
#    static-path-pattern: /res/**

  resources:
    add-mapping: false // 不让静态资源访问
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

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

	/**
	 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
	 * /resources/, /static/, /public/].
	 */
	private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
	}
  1. 欢迎页的处理规则
    HandlerMapping ,处理器映射,保存了每一个Handler能够处理那些请求
@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
				FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
			return welcomePageHandlerMapping;
		}

WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
			ApplicationContext applicationContext, Optional<Resource> welcomePage, String staticPathPattern) {
		if (welcomePage.isPresent() && "/**".equals(staticPathPattern)) {
		// 要用欢迎页功能,必须是/**
			logger.info("Adding welcome page: " + welcomePage.get());
			setRootViewName("forward:index.html");
		}
		else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
		// 调用Controller/index
			logger.info("Adding welcome page template: index");
			setRootViewName("index");
		}
	}

3、数据访问

4、单元测试

5、指标监控

6、原理解析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值