一只胡说八道的猴子

资讯 2024-07-10 阅读:53 评论:0
美化布局示例

欧易(OKX)最新版本

【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   全球官网 大陆官网

币安(Binance)最新版本

币安交易所app【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址

火币HTX最新版本

火币老牌交易所【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址

Spring Boot是Spring项目中的一个子工程,与我们所熟知的Spring-framework 同属于spring的产品:

Spring Boot is a sub-engineering project in Spring, a product that we know as Spring-framework that belongs to Spring:

首页Spring Boot官方介绍简介可以看到下面的一段介绍

The official introduction to Spring Boot on the front page of

Spring Boot的设计目的是让您尽可能快地启动和运行,而无需预先配置Spring。Spring Boot以一种固定的方式来构建可用于生产级别的应用程序。

Spring Boot is designed to enable you to start and run as quickly as possible, without having to pre-configurate Spring.

在这里插入图片描述

 insert

一般把Spring Boot称为搭建程序的脚手架 或者说是便捷搭建 基于Spring的工程 脚手架。其最主要作用就是帮助开发人员快速的构建庞大的spring项目,并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让开发人员关注业务而非配置。

Spring Boot is commonly referred to as a scaffolding for building programs, or as an easy scaffolding of Spring-based engineering projects. Its primary role is to help developers quickly build large Spring projects, and to minimize all Xml configurations, so that they can be open, quickly start, and let developers focus on business rather than configuration.

传统项目的缺点:

java一直被人诟病的一点就是臃肿、麻烦。当我们还在辛苦的搭建项目时,可能Python程序员已经把功能写好了,究其原因注意是两点:

One of the problems that Java has been suffering from is swollen and trouble. When we've been working hard on the project, perhaps Python's programmer has already written the function for two reasons:

1.复杂的配置

项目各种配置其实是开发时的损耗, 因为在思考 Spring 特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写应用程序逻辑的时间。

The various configurations of the project are actually a loss in development because writing the configuration takes time to write the application logic because there is a need for a change of mind between thinking about the Spring feature configuration and solving business problems.

2.一个是混乱的依赖管理

项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这难题实在太棘手。并且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。

The difficulty of deciding which banks to use in a project are painful enough, and you also need to know which versions of these libraries are not in conflict with others, is too difficult. And, depending on management is also a loss, adding reliance is not an application code.

3.而Spring Boot让这一切成为过去!

Spring Boot 简化了基于Spring的应用开发,只需要“run”就能创建一个独立的、生产级别的Spring应用。Spring Boot为Spring平台及第三方库提供开箱即用的设置(提供默认设置,存放默认配置的包就是启动器starter),这样我们就可以简单的开始。多数Spring Boot应用只需要很少的Spring配置。我们可以使用Spring Boot创建java应用,并使用java –jar 启动它,就能得到一个生产级别的web工程。

Spring Boot simplifies Spring-based application development by creating a stand-alone production-level Spring application only if “run” is needed. Spring Boot provides open-to-box settings for the Spring platform and third-party libraries (provides default settings, the package containing the default configuration is starter) so that we can start simply. Most Spring Boot applications require very few Spring configurations. We can create java applications using Spring Boot and start it with java-jar, and we can get a production-level web project.

1.创建独立的Spring应用,为所有 Spring 的开发者提供一个非常快速的、广泛接受的入门体验
2.直接嵌入应用服务器,如tomcat、jetty、undertow等;不需要去部署war包
3.提供固定的启动器依赖去简化组件配置;实现开箱即用(启动器starter-其实就是Spring Boot提供的一个jar包),通过自己设置参数(.properties或.yml的配置文件),即可快速使用。
4.自动地配置Spring和其它有需要的第三方依赖
5.提供了一些大型项目中常见的非功能性特性,如内嵌服务器、安全、指标,健康检测、外部化配置等
6.绝对没有代码生成,也无需 XML 配置

1. Creates a stand-alone Spring application that provides a very rapid and widely accepted introduction experience for all Spring developers
2.
directly embedded application servers such as Tomcat, jetti, undertow, etc.; does not need to deploy warbags
3. to provide a fixed starter that relies on the simplification of the configuration of the components; the opening of boxes (starter Starter - a Jar package that is actually provided by Spring Boot) provides a number of non-functional features common to large projects, such as embedded servers, security indicators, health testing, external configurations, etc.
strong > 4. Automatic 6.

能够使用Spring Boot搭建项目

Can build projects using Spring Boot

需求:可以在浏览器中访问http://localhost:8080/hello输出一串字符
默认端口为8080

Demand: The default port of
is 8080 , which can be accessed from the browser at http://localhost:8080/ello

  1. 创建工程;
  2. 添加依赖(启动器依赖,spring-boot-starter-web);
  3. 创建启动类;
  4. 创建处理器Controller;
  5. 测试

1. 创建工程;

创建一个普通的maven工程

Creates a normal maven project

在这里插入图片描述

insert picture description

2. 添加依赖(启动器依赖,spring-boot-starter-web);


3. 创建启动类;

springBott工程都有一个启动类,这是工程的入口类并在引导类上添加@SpringBootApplication注解,该注解包含扫描会扫描到当前包及其子包下的所有注解

The SpringBot project has a start-up class, which is the project's entry class and adds to the guide category @SprintBootApplication note, which contains a scan of all the notes under the current bag and its sub-pack.

![image.png](https://img-blog.csdnimg.cn/img_convert/33a057e9c5ab629f28bc39a440b71776.png#align=left&display=inline&height=217&margin=[object Object]&name=image.png&originHeight=338&originWidth=657&size=47474&status=done&style=none&width=422)


4. 创建处理器Controller

**
@RestController包含以下注解
在这里插入图片描述

**
@RestController contains note

insert picture description


5. 测试

在这里插入图片描述

Spring-boot可以在没有任何的xml的情况下配置Bean,比如我们要配置一个数据库连接池,以前会这么配置:

Spring-boot can configure Bean without any xml, e.g. we have to configure a database connection pool, which used to be:



事实上,在Spring3.0开始,Spring官方就已经开始推荐使用java配置来代替传统的xml配置了,我们不妨来回顾一下
Spring的历史:

In fact, when Spring 3.0 started, Spring's officials had started to recommend Java instead of the traditional xml configuration, so let's look back at the history of
strong>Sprint: .

Spring1.0时代

在此时因为jdk1.5刚刚出来,注解开发并未盛行,因此一切Spring配置都是xml格式,想象一下所有的bean都用xml配置,细思极恐啊,心疼那个时候的程序员2秒

At this point, since jdk1.5 had just come out and the annotation was not popular, all Spring configurations were Xml formatted. Imagine all bean configurations with Xml.

Spring2.0时代

Spring引入了注解开发,但是因为并不完善,因此并未完全替代xml,此时的程序员往往是把xml与注解进行结合,貌似我们之前都是这种方式。

Spring has introduced a note development, but because it is not perfect, it is not entirely a substitute for xml, which the programmer often combines with the note, as if we had done before.

Spring3.0及以后

3.0以后Spring的注解已经非常完善了,因此Spring推荐大家使用完全的java配置来代替以前的xml,不过似乎在国内并未推广盛行。然后当Spring Boot来临,人们才慢慢认识到java配置的优雅。有句古话说的好:拥抱变化,拥抱未来。所以我们也应该顺应时代潮流,做时尚的弄潮儿,一起来学习下java配置的玩法

After 3.0, Spring's notes were perfect, so Spring recommended that you replace the former xml with a full Java configuration, although it didn't seem to be popular in the country. Then when Spring Boot arrived, people slowly realized the grace of Java's configuration. There's a saying: Embrace change, embrace the future. So let's learn how to do the Java configuration.

java配置主要靠java类和一些注解,比较常用的注解有:
@Configuration :声明一个类作为配置类,代替xml文件@Bean :声明在方法上,将方法的返回值加入Bean容器,代替 标签@Value :属性注入@PropertySource :指定外部属性文件,

java configuration is based mainly on the Java class and some notes, which are more commonly used: br>@Configuration: declares a class as a configuration class instead of the xml document @Bean: states that the return value of the method is methodologically added to the Bean container to replace the tag @Value: attribute to @PropertySource: specifies an external attribute file,

案例

目标:可以使用@Value获取配置文件配置项并结合@Bean注册组件到Spring

Target: Profile configurations can be obtained using @Value and linked to @Bean's registered component to Spring

分析
需求:使用Java代码配置数据库连接池,并可以在处理器中注入并使用
步骤

Analysis :
Needs
: Configure the database connections pool using Java code, and can be injected into the processor and use
steps :

  1. 添加依赖;
  2. 创建数据库;
  3. 创建数据库连接参数的配置文件jdbc.properties;
  4. 创建配置类;
  5. 改造处理器类注入数据源并使用

添加依赖;

Add dependency;


创建数据库;
在这里插入图片描述

Creates a database; inserts

创建数据库连接参数的配置文件jdbc.properties;

creates profile for database connection parametersjdbc.properties;


**
创建配置类;
**

**br < strong> creates configuration class; **


**
改造处理器类注入数据源并使用

**
transform processor type injects data sources and uses



案例

目标:能够使用@ConfigurationProperties实现Spring Boot配置文件配置项读取和应用

Objective: can read and apply the Spring Boot profile with @ConfigurationProperties

分析:
**
需求:将配置文件中的配置项读取到一个对象中;

analysis:
**br> needs: read the configuration in the configuration file to an object;

实现:可以使用Spring Boot提供的注解@ConfigurationProperties,该注解可以将Spring Boot的配置文件(默认必须为application.properties或application.yml)中的配置项读取到一个对象中。
**
实现步骤:
**
**1. **创建配置项类JdbcProperties类,在该类名上面添加@ConfigurationProperties;

Achieved: could use the notes provided by Spring Boot @ConfigurationProperties, which could read an object from the configuration file of Spring Boot (by default must be read to application.properties or application.yml).
**br> >


> **1. ** Create configuration class JdbcProperties with the addition of @ConfutureProperties;

**2. **将jdbc.properties修改名称为application.properties;

**2. ** Changed the name of jdbc.properties to application.properties;

3. 将JdbcProperties对象注入到JdbcConfig;

3. injects JdbcProperties objects into JdbcConfig;

**4. **测试

**4. ** Tests

1. 创建配置项类JdbcProperties类,在该类名上面添加@ConfigurationProperties;

1. Creates an configuration class of the JdbcProperties class by adding to this class name@ConfigurationProperties;

ConfigurationProperties 从application配置文件中读取配置项
** prefix 表示 配置项的前缀**
** 配置项类中的类变量名必须要与 前缀之后的配置项名称保持 松散绑定(相同)**

ConfigurationProperties Read configuration item
from application configuration file ** prefix indicates that configuration item prefix**
** The class variable name in the configuration class must be kept with the configuration item name after the prefix


**2. **将jdbc.properties修改名称为application.properties;

**2. ** Changed the name of jdbc.properties to application.properties;


3. 将JdbcProperties对象注入到JdbcConfig;

3. injects JdbcProperties objects into JdbcConfig;

通过 @EnableConfigurationProperties(JdbcProperties.class) 来声明要使用 JdbcProperties 这个类的对象
然后要使用配置的话;可以通过以下方式注入JdbcProperties:

Declares the use of objects in the JdbcProperties class
by @EnableConfigurationProperties(JdbcProperties.clas) and then uses configurations; JdbcProperties can be injected by:

注入方式1
方法参数注入


注入方式2

injection mode 2

@Autowired注入

@Autowired Injected


注入方式3

injection mode 3

构造函数注入

Construct function injection


**4. **测试

**4. ** Tests

在这里插入图片描述

 insert

优雅的SpringBoot注入方式

事实上,如果一段属性只有一个Bean需要使用,我们无需将其注入到一个类(JdbcProperties,将该类上的所有注解去掉)中。而是直接在需要的地方声明即可;再次修改 JdbcConfig 类为如下

In fact, if there's only one Bean that needs to be used, we don't need to inject it into a class (JdbcProperties, delete all notes from that class). Instead, we can state it directly where it is needed; re-modify the JdbcConfig to read as follows.

代码:

code:


我们直接把 @ConfigurationProperties(prefix="jdbc") 声明在需要使用的 @Bean 的方法上,然后SpringBoot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。使用的前提是:该类必须有对应属性的set方法(即对应的名称与set方法的名称要一致)!

@ConfigurationProperties(prefix="jdbc") states that it is necessary to use the @Bean method, and then SpringBoot automatically calls the set method of the Bean (in this case, DataSource) and then completes the injection. The premise used is that must have a set method (i.e. the corresponding name corresponds to the name of the set method)!

注意事项:
这种读取方式不需要创建对应的类,是直接读取配置文件中以"jdbc"为前缀的项,然后自动的匹配方法中要返回值的属性,把与jdbc中对应后缀的名称与类中对应的属性的名称一致的自动匹配,自动注入

Note:
read without creating a corresponding class, reading directly the prefix "jdbc" in the configuration file, then returning the properties of the value in the automatic matching method, automatically matching the name of the corresponding suffix in jdbc with the name of the corresponding attribute in the class, automatically infusing

YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据数据序列化格式,并且容易被人类阅读, 容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,比如: C/C++, Ruby, Python, Java, Perl, C#, PHP等。YML文件是以数据为核心的,比传统的xml方式更加简洁。 YML文件的扩展名可以使用.yml或者.yaml

The YML file format is a document format prepared by YAML (YAML Aint Markup Language). YAML is a visual, computer-recognizable data data sequence format that is easily read by humans, is easily interactive with script language and can be imported into different programming language programs that support YAML library, such as: C/C++, Ruby, Python, Java, Perl, C#, PHP, etc. YML files are data-centred and are more concise than traditional xml. The YML file extension can be used.yml or.yaml

在这里插入图片描述

insert picture description

  1. 树状层级结构展示配置项;
  2. 配置项之间如果有关系的话需要分行空两格;
  3. 配置项如果有值的话,那么需要在 之后空一格再写配置项值;

将application.properties配置文件修改为application.yml的话:

Change the application.properties profile to application.yml

propeties文件

propecies


yml文件

yml/strong>




多个yml配置文件:

在spring boot中是被允许的。这些配置文件的名称必须为application-***.yml,并且这些配置文件必须要在application.yml配置文件中激活之后才可以使用。
**
案例
**
比如有两个配置文件application-abc.yml,application-def.yml

These configuration files must be named as application-***.yml, and they must be activated in the application.yml configuration file before they can be used.
br> case
br> such as two configuration-abc.yml, application-def.yml


如果properties和yml配置文件同时存在在spring boot项目中:

那么这两类配置文件都有效。在两个配置文件中如果存在同名的配置项的话会以properties文件的为主。

Both profiles are valid. If there is a configuration with the same name in both profiles, the profile is dominated by the profile.

yml配置普通数据

语法: key: value

Syntax: Key: value


配置对象数据||配置Map数据

语法:
key:
key1: value1
key2: value2
** 或者:**
key: {key1: value1,key2: value2}

syntax: Key:
Key1: value1
key2: value2
** Or: br> key: {key1: value1, Key2: value2}

示例代码

example code


配置数组(List、Set)数据

语法
key:

Syntax:
key:

  • value1
  • value2
    或者:
    key: [value1,value2]

注意:value1与之间的 - 之间存在一个空格
例子:

notes that there is an example of a space between
:

整合




使用Spring Boot之后,一个整合了SpringMVC的WEB工程开发,变的无比简单,那些繁杂的配置都消失不见了,这是如何做到的?
一切魔力的开始,都是从我们的main函数来的,所以我们再次来看下启动类:

After using Spring Boot, a WEB project that integrated SpringMVC was developed, and it was so simple that all the complex configurations disappeared, how did this happen?
All the magic starts with our main function, so let's look again at the starting class:

在这里插入图片描述

 insert

我们发现特别的地方有两个:
注解:@SpringBootApplication
run方法:SpringApplication.run()我们分别来研究这两个部分

We found two special features:
notes: @SprintBootApplication
run Method: SpringApplication.run() We're looking at each of these two parts.

点击进入,查看源码:

Click into, view source:

在这里插入图片描述

这里重点的注解有3个:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan

highlights three notes:
@SpringBootConfuture
@EnableAutoConfuture
@ComponentScan

@SpringBootConfiguration

在这里插入图片描述

 insert

通过这段我们可以看出,在这个注解上面,又有一个 @Configuration 注解。通过上面的注释阅读我们知道:这个注解的作用就是声明当前类是一个配置类,然后Spring会自动扫描到添加了 @Configuration 的类,并且读取其中的配置信息。而 @SpringBootConfiguration 是来声明当前类是SpringBoot应用的配置类,项目中只能有一个。所以一般我们无需自己添加。

As we can see from this note, there is another @Configuration note. Read through the notes above, we know that the note is meant to state that the current class is a configuration class, and then Spring automatically scans into the added class of @Configuration and reads the configuration information. @SpringBootConfuture is meant to state that the current class is a configuration class for SpringBoot applications, and there is only one item in the project. So we do not usually have to add it ourselves.

@EnableAutoConfiguration

关于这个注解,官网上有一段说明
第二级的注解 @EnableAutoConfiguration ,告诉Spring Boot基于你所添加的依赖,去“猜测”你想要如何配置Spring。比如我们引入了 spring-boot-starter-web ,而这个启动器中帮我们添加了 tomcat 、 SpringMVC的依赖。此时自动配置就知道你是要开发一个web应用,所以就帮你完成了web及SpringMVC的默认配置了!

On this note, the official's website has a note :
to the second level > to tell SpringBoot how you want to configure Spring based on your added dependence. For example, we introduced Spring-boot-Starter-web, and this trigger added to our tomcat, SpringMVC dependency. The automatic configuration at this point knows that you want to develop a web application, so it helped you with the default configuration of Web and SpringMVC!

总结:

summary:

Spring Boot内部对大量的第三方库或Spring内部库进行了默认配置,这些配置是否生效,取决于我们是否引入了对应库所需的依赖,如果有那么默认配置就会生效。所以,我们使用SpringBoot构建一个项目,只需要引入所需框架的依赖,配置就可以交给SpringBoot处理了。除非你不希望使用SpringBoot的默认配置,它也提供了自定义配置的入口。

The default configuration within Spring Boot of a large number of third-party libraries or Spring internal libraries is valid, depending on whether we have introduced the required reliance on the corresponding library, and if so, the default configuration. So, we use SpringBoot to build a project by introducing the required framework, and the configuration is left to SpringBoot. Unless you do not want to use SpringBoot's default configuration, it also provides a custom configuration entry.

@ComponentScan

我们跟进源码

We follow the source code :

在这里插入图片描述

insert picture description

并没有看到什么特殊的地方。我们查看注释:

doesn't see anything special. Let's look at the note:

在这里插入图片描述

insert picture description

大概的意思:
配置组件扫描的指令。提供了类似与 context:component-scan 标签的作用
通过basePackageClasses或者basePackages属性来指定要扫描的包。如果没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包
而我们的@SpringBootApplication注解声明的类就是main函数所在的启动类,因此扫描的包是该类所在包及其子包。因此,一般启动类会放在一个比较前的包目录中

approximation: command for the configuration component scan. Provides a function similar to that of confext:compont-scan tag
, which specifies the package to be scanned through the basePackageClasses or basePackages properties. If these properties are not specified, the scan package and the sub-pack will start with the package that states the type to be specified, and our @SpringBootApplication comment class is the start-up class of the main function, so the scanned package is the type of bag and its sub-packs.

在SpringApplication类构建的时候,有这样一段初始化代码:

在这里插入图片描述

 insert

跟进去:
在这里插入图片描述

following:

这里发现会通过loadFactoryNames尝试加载一些FactoryName,然后利用createSpringFactoriesInstances将这些加载到的类名进行实例化。继续跟进loadFactoryNames方法:
在这里插入图片描述

finds that there will be an attempt to load some FactoryNames via RoadFactoryNames, and then exemplify these types of names that are loaded using createSpringFactoriesInstances. Follow up on the loadFactoryNames method:

发现此处会利用类加载器加载某个文件: FACTORIES_RESOURCE_LOCATION ,然后解析其内容。我们找到这个变量的声明:

finds that a file is loaded here using a class loader: FACTORIAs_RESOURCE_LOCATION and then interprets its contents. We find the statement of this variable:

在这里插入图片描述

insert picture description

可以发现,其地址是: META-INF/spring.factories ,我们知道,ClassLoader默认是从classpath下读取文件,因此,SpringBoot会在初始化的时候,加载所有classpath:META-INF/spring.factories文件,包括jar包当中的。而在Spring的一个依赖包:spring-boot-autoconfigure中,就有这样的文件:
在这里插入图片描述

finds that its address is: META-INF/spring.factories, and we know that Clas Loader is by default reading the files from monospath, so SpringBoot will load all classpath: META-INF/spring.factors, including in jar bags. In Spring: Spring-boot-autoconfiguure, there are documents: , and are reproduced in >.

**以后我们引入的任何第三方启动器,只要实现自动配置,也都会有类似 **

** Any third-party starter that we'll introduce later, as long as it's automatically configured, will be similar **

我们打开刚才的spring.factories文件:
在这里插入图片描述

We open the earlier Spring.factories file:

可以发现以EnableAutoConfiguration接口为key的一系列配置,key所对应的值,就是所有的自动配置类,可以在当前的jar包中找到这些自动配置类:
在这里插入图片描述

can find a series of configurations for key using the EnableAutoConfiguration interface, corresponding to all automatic configurations, which can be found in the current jar package:

非常多,几乎涵盖了现在主流的开源框架,例如:
redis
jms
amqp
jdbc
jackson
mongodb
jpa
solr
elasticsearch
... 等等
我们来看一个我们熟悉的,例如SpringMVC,查看mvc 的自动配置类:

在这里插入图片描述
**

contains a large number of open source frameworks that cover almost all of the current mainstream, e.g.: redis
jms
amqp
jdbc
jackson
mongodb
jpa
jpa
solr
Elasticsearch

, etc.;
, e.g. SpringMvC, e.g. SpringMvC, e.g. img src= "https://mg-blog.csdnimg.cn/202209210508810png?x-oss-proces=image/watermark, type_ZZ3ZW5naGk>, , , op.int_lwlwl_vl_vl_l_l_vl_vl_vl_l_l_vl_vl_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l_l

打开WebMvcAutoConfiguration:

**

在这里插入图片描述

Page description

我们看到这个类上的4个注解:
**@Configuration :声明这个类是一个配置类@ConditionalOnWebApplication(type=Type.SERVLET)ConditionalOn,翻译就是在某个条件下,此处就是满足项目的类是是Type.SERVLET类型,也就是一个普通web工程,显然我们就是@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })这里的条件是OnClass,也就是满足以下类存在:Servlet、DispatcherServlet、WebMvcConfigurer,其Servlet只要引入了tomcat依赖自然会有,后两个需要引入SpringMVC才会有。这里就是判断你是否引入了相关依赖,引入依赖后该条件成立,当前类的配置才会生效!@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)这个条件与上面不同,OnMissingBean,是说环境中没有指定的Bean这个才生效。其实这就是自定义配置的入口,也就是说,如果我们自己配置了一WebMVCConfigurationSupport的类,那么这个默认配置就会失效!
接着,我们查看该类中定义了什么:
**

We see four notes on this category:
**@Configuration: this class is declared to be a configuration class @ConditionalOnWebApplication (type=Type.SERVLET)ConditionalOn, under certain conditions, where it is satisfied that the type of project is Type.Servlet, a general web project, and apparently we are @ConditionOnClass ({Servlet.clas, DespackerServeSelvlas, WebMvConfunger.Class}) The condition is that OnClass, i.e. that the following categories are satisfied: Servlet, DispatcherServesServes, WebCongener, that is the condition that we're not able to use , which means that we're not able to introduce the configuration of the configuration of Business.

视图解析器:

在这里插入图片描述

 insert

处理器适配器(HandlerAdapter):
在这里插入图片描述

processor adapter (HandlerAdapter):

Page description

我们看到,这里通过@EnableAutoConfiguration注解引入了两个属性:WebMvcProperties和ResourceProperties。这不正是SpringBoot的属性注入玩法嘛。
我们查看这两个属性类:

在这里插入图片描述

We see that two attributes have been introduced here through a note from @EnableAutoConfiguration: WebMvProperties and ResourcesProperties. It's not exactly SpringBoot's properties that are injected into the game.
We look at these two properties:

 insert

**如果我们要覆盖这些默认属性,只需要在application.properties中定义与其前缀prefix和字段名一致的属性即可。 **

** If we want to overwrite these default properties, we just need to define properties in application.properties that match their prefix prefix prefix and field name.**

SpringBoot为我们提供了默认配置,而默认配置生效的步骤:

1.@EnableAutoConfiguration注解会去寻找 META-INF/spring.factories 文件,读取其中以EnableAutoConfiguration 为key的所有类的名称,这些类就是提前写好的自动配置类

1. @EnableAutoConfiguration notes will look for META-INF/spring.factories to read the names of all classes of which EnableAutoConfiguration is the type of automatic configuration written in advance.

2.这些类都声明了 @Configuration 注解,并且通过 @Bean 注解提前配置了我们所需要的一切实例

2. All these classes have stated @Configuration and pre-configuring all the examples we need by @Bean

3.但是,这些配置不一定生效,因为有 @ConditionalOn 注解,满足一定条件才会生效。比如条件之一: 是一些相关的类要存在

3. However, these configurations do not necessarily take effect because there are @ConditionalOn notes that satisfy certain conditions for validity. For example, one condition is that some related categories exist.

4.类要存在,我们只需要引入了相关依赖(启动器),依赖有了条件成立,自动配置生效。
5.如果我们自己配置了相关Bean,那么会覆盖默认的自动配置的Bean

For the class to exist, we just need to introduce the relevant dependency (starter), which is created and automatically configured.
5. If we configure the relevant Bean ourselves, the default automatic configuration of Bean will be covered.

6.我们还可以通过配置application.yml文件,来覆盖自动配置中的属性

6. We can also overwrite properties in autoconfiguration by configuring application.yml files

1)启动器

所以,我们如果不想配置,只需要引入依赖即可,而依赖版本我们也不用操心,因为只要引入了SpringBoot提供的stater(启动器),就会自动管理依赖及版本了。
因此,玩SpringBoot的第一件事情,就是找启动器,SpringBoot提供了大量的默认启动器

So if we don't want to configure it, we just need to introduce dependence, and we don't have to worry about relying on the version, because as long as we have introduced the stateer (starter) provided by SpringBoot, we automatically manage the dependency and the version.
So the first thing to play SpringBoot is to find a starter, and SpringBoot provides a lot of default triggers.

2)全局配置

另外,SpringBoot的默认配置,都会读取默认属性,而这些属性可以通过自定义 application.properties 文件来
进行覆盖。这样虽然使用的还是默认配置,但是配置中的值改成了我们自定义的。
因此,玩SpringBoot的第二件事情,就是通过 application.properties 来覆盖默认属性值,形成自定义配置。我
们需要知道SpringBoot的默认属性key,非常多,可以再idea中自动提示

Furthermore, the default configuration of SpringBoot will read the default properties, which can be covered by custom application.properties files
. This is how the default configuration is used, but the value in the configuration has been changed to our custom.
So the second thing to play SpringBoot is to overwrite the default attribute values through application.properties to create a custom configuration. I
need to know the default properties of SpringBoot, which is a lot, which can be automatically hinted in the idea.

属性文件支持两种格式,application.properties和application.yml
yml的语法实例:

The attribute files support two formats, examples of syntaxes for application.properties and application.yml
yml:


如果properties和yml文件都存在,如果有重叠属性,默认以Properties优先。遇到需要修改的组件的配置项流程为:

If both the properties and yml files exist, if there are overlapping properties, the default priority is the Properties. The configuration process for components that need to be modified is as follows:

在这里插入图片描述

 insert

Lombok是一个可以通过简单的注解形式来帮助我们简化消除一些必须有但显得很臃肿的Java代码的工具,通过使用对应的注解,可以在编译源码的时候生成对应的方法

Lombok is a tool that can help us simplify the elimination of some of Java's code that must be swollen but that can be generated when compiling the source code by using the corresponding note.

步骤1

File->setting->Plugins ,然后搜索lombok
在这里插入图片描述

File-> setting-> Plugins, then search for Lombok
 inserts a description of 步骤二

在pom.xml文件中导入相关的依赖

Import Related Dependence in Pom.xml File



@Getter and @Setter

你可以用@Getter / @Setter注释任何字段(当然也可以注释到类上的),让lombok自动生成默认的getter / setter方法。
默认生成的方法是public的,如果要修改方法修饰符可以设置AccessLevel的值,例如:@Getter(access=AccessLevel.PROTECTED)
**

You can use @Getter/ @Setter to comment on any field (and, of course, to the class) to allow Lombok to automatically generate the default geter/ setter method.
The default generation method is public. If you want to modify the modifier method, you can set AccessLive @Getter(access=AccessLive. PROTECTED)
**

在这里插入图片描述

,


@ToString

生成toString()方法,默认情况下,它会按顺序(以逗号分隔)打印你的类名称以及每个字段。可以这样设置不包含哪些字段@ToString(exclude="id") / @ToString(exclude=)
如果继承的有父类的话,可以设置callSuper 让其调用父类的toString()方法,例如:@ToString(callSuper=true)

Generates tostring() method, which, by default, will print your class name in sequence (separated by commas) as well as each field. This can be done by setting out the fields that do not contain @Tostring(exclude=id) /strung> @Tostring (exclude=) >, if the successor has a parent, setting calll Super, for example: @Tostring(callSuper=true> >.


生成toString方法如下:

Tostring is generated by:


@EqualsAndHashCode

生成hashCode()和equals()方法,默认情况下,它将使用所有非静态,非transient字段。但可以通过在可选的exclude参数中来排除更多字段。或者,通过在parameter参数中命名它们来准确指定希望使用哪些字段。

Generates the HashCode() and equals() methods, which, by default, will use all non-static, non-transient fields. However, more fields can be excluded by using optional exclude parameters. Or, by naming them in parameter parameters, specify precisely which fields you want to use.


对比代码如下:

The comparison code is as follows:


  • @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor

@NoArgsConstructor生成一个无参构造方法。当类中有final字段没有被初始化时,编译器会报错,此时可用@NoArgsConstructor(force=true),然后就会为没有初始化的final字段设置默认值 0 / false / null。对于具有约束的字段(例如@NonNull字段),不会生成检查或分配,因此请注意,正确初始化这些字段之前,这些约束无效。

@NoArgsConstructor generates a non-descriptive construction method. When there is a binal field in the class that is not initialized, the compiler is wrong. It can be used at @NoArgsConstructor(force=true), and then the default value 0/ false/ null is set for the non-informed final field. For bound fields (e.g. @NonNull field), the check or allocation is not generated, so note that these restrictions are invalid before the correct initialization of the field.


@RequiredArgsConstructor会生成构造方法(可能带参数也可能不带参数),如果带参数,这参数只能是以final修饰的未经初始化的字段,或者是以@NonNull注解的未经初始化的字段
@RequiredArgsConstructor(staticName="of")会生成一个of()的静态方法,并把构造方法设置为私有的

@RequiredArgsConstructor will generate a construction method (possibly with or without parameters) which, if accompanied by parameters, can only be based on an uninitialized field modified by the vinal, or
with an uninitial field @NonNull annotated by @RequiredArgsConstructor (staticName = "of") will generate a static method of lf() and set the construction method to private.

在这里插入图片描述

在这里插入图片描述

 insert


@AllArgsConstructor 生成一个全参数的构造方法

在这里插入图片描述


@Data

@Data 包含了 @ToString、@EqualsAndHashCode、@Getter / @Setter和@RequiredArgsConstructor的功能

@Data contains @ToString, @EqualsAndHashCode, @Getter/ @Setter and @RequiredArgsConstructor

@Accessors

@Accessors 主要用于控制生成的getter和setter
主要参数介绍

@Accessors mainly used to control generation of key parameters

  • fluent boolean值,默认为false。此字段主要为控制生成的getter和setter方法前面是否带get/set
  • chain boolean值,默认false。如果设置为true,setter返回的是此对象,方便链式调用方法
  • prefix 设置前缀 例如:@Accessors(prefix="abc") private String abcAge 当生成get/set方法时,会把此前缀去掉

在这里插入图片描述

 insert

@Synchronized

给方法加上同步锁

Put a synchronised lock on the method.



@Wither

提供了给final字段赋值的一种方法

It provides a way to give value to the final field.



@onX

在注解里面添加注解的方式

How to add an annotation to the note.

直接看代码

Look directly at the code.


@Builder

@Builder注释为你的类生成复杂的构建器API。
lets you automatically produce the code required to have your class be instantiable with code such as:

@Builder comments to generate complex builders for your class API.


直接看官方示例,对比一下就都明白了

Just look at the official example and we'll see.



@Delegate

这个注解也是相当的牛逼,看下面的截图,它会该类生成一些列的方法,这些方法都来自与List接口

This note is also quite awesome. Look at the screenshot below. It creates some sort of column approach, all of which comes from interfaces with List.

在这里插入图片描述

 insert

附带一个我使用的例子

就介绍这么多了,更多的注解请看官方文档

虽然默认配置已经可以使用SpringMVC了,不过我们有时候需要进行自定义配置。
可以在 application.yml 文件中配置日志级别控制:

Although the default configuration is already available using SpringMVC, we sometimes need custom configuration.
Configure log level control in application.yml files:

查看SpringBoot的全局属性可知,端口通过以下方式配置:

View the global properties of SpringBoot, the port is configured as follows:


修改 application.yml 配置文件,添加如下配置:

Modify application.yml profile to add the following configuration:


重启服务后测试:

Post-service testing:

在这里插入图片描述

Page description

现在,我们的项目是一个jar工程,那么就没有webapp,我们的静态资源该放哪里呢?
回顾我们在上面看的源码,有一个叫做ResourceProperties的类(路径:org.springframework.boot.autoconfigure.web.ResourceProperties),里面就定义了静态资源的默认查找路径:
默认的静态资源路径为:

Now, our project is a jar project, so where do we put our static resources without Webapp?
recalls the source code we see above, and there is a class called ResourcesProperties (path: org. Springframework.boot.autoconfigure.web.ResourceProperties)


只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理。
**我们习惯会把静态资源放在 classpath:/static/ 目录下。我们创建目录 static **,
在这里插入图片描述

As long as static resources are in any one of these directories, SpringMVC will help us handle them.
** We're used to putting static resources under classpath:/static/ directory. We create directory status **,
loading=


注意:如果访问图片时候没有显示;可以先将项目先clean再启动,或者创建 public、resources 文件夹,然后图片放置到public或resources中。

Note: If images are not shown when they are visited, you can either start the project first, or create a public, resources folder, and then place the picture in public or resources.

拦截器介绍

拦截器也是我们经常需要使用的,在SpringBoot中该如何配置呢?
拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。

Interceptors are also what we often need to use, and how should they be configured in SpringBoot?
Interceptors are not ordinary properties, but a class, so they're going to be used in the Java configuration.

在SpringBoot官方文档中有这么一段说明:
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 @Configurationclass of type WebMvcConfigurer but without @EnableWebMvc . If you wish to provide custom instances of RequestMappingHandlerMapping , RequestMappingHandlerAdapter , orExceptionHandlerExceptionResolver , 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 @Configuration annotated with @EnableWebMvc .
**
翻译:如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器,视图控制器、消息转换器 等等),你应该让一个类实现 WebMvcConfigurer ,并且添加 @Configuration 注解,但是千万不要加 @EnableWebMvc 注解。如果你想要自定义HandlerMappingHandlerAdapter 、ExceptionResolver 等组件,你可以创建一个 WebMvcRegistrationsAdapter 实例 来提供以上组件。如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一切特征,你可以自己定义类并且添加@Configuration 注解和 @EnableWebMvc 注解

in SpringBoot Official Document, you can add your home @Confutures of type WebConfuture but without @EnableWebmvc. If you wish to use the RequestMandlerMapping, RequeMapplatorMantures and others Featurres), you can add your home @Confutures of type webMvCongourer but not @EnableWebCretrem.

总结:通过实现 WebMvcConfigurer 并添加 @Configuration 注解来实现自定义部分SpringMvc配置。

Summary: accomplishes the custom SprintMvc configuration by achieving WebMvcConfigurer and adding @ConfigurationNote.

案例

配置一个拦截器


注册一个拦截器


接下来访问http://localhost/hello 并查看日志:

Below is a visit to http://localhost/ello and a view of the log:

在这里插入图片描述

 insert

spring中的jdbc连接和事务是配置中的重要一环,在SpringBoot中该如何处理呢?
答案是不需要处理,我们只要找到SpringBoot提供的启动器即可,在 pom.xml 文件中添加如下依赖:

Jdbc connection and service in Spring is an important part of the configuration. What should we do in SpringBoot?
The answer is that we don't need to deal with it. We just need to find the starter provided by SpringBoot. Add the following reliance in the Pom.xml file:


当然,不要忘了数据库驱动,SpringBoot并不知道我们用的什么数据库,这里我们选择MySQL;同样的在 pom.xml文件中添加如下依赖:

Of course, don't forget the database driver, SpringBoot doesn't know what database we're using, and here we choose MySQL; the same is to add the following reliance to the Pom.xml file:


至于事务,SpringBoot中通过注解来控制。就是我们熟知的 @Transactional 使用的时候设置在对应的类或方法上即可。

As far as business is concerned, the SpringBoot is controlled by an annotation. That's what we know about @Transactional when it's used.

目标:

配置Spring Boot自带默认的hikari数据库连接池和使用@Transactional注解进行事务配置

Configure Spring Boot's own default hikari database connection pool and use @Transactional annotation for service configuration

分析:

1.添加事务相关的启动器依赖,mysql相关依赖
2.编写业务类UserService使用事务注解@Transactional
3.数据库连接池hikari配置
只需要在application配置文件中指定数据库相关参数

Add service-related starter reliance, Mysql-related reliance
2. Preparation of business class UserService User Notes @Transactional
3.

1.添加事务相关的启动器依赖,mysql相关依赖


2.编写业务类UserService使用事务注解@Transactional

加了@Transactional注解的方法中的内容要不全部执行成功要不回滚

If you don't get all the content in the @Transactional note, you don't have to go back.


3.数据库连接池hikari配置

**引入jdbc启动器的时候,SpringBoot已经自动帮我们引入了hikari连接池 **
**

** When the jdbc starter was introduced, SpringBoot automatically introduced the hikari connection pool **br **

在这里插入图片描述

 insert

**HikariCP应该是目前速度最快的连接池了,我们看看它与c3p0的对比 **

** HikariCP is supposed to be the fastest connection pool at the moment. ** Let's see how it compares to c3p0.**

在这里插入图片描述

Page description

只需要在application配置文件中指定数据库相关参数


直接在要使用的地方注入即可使用
**

can be used directly in the place to use
**




SpringBoot官方并没有提供Mybatis的启动器,不过Mybatis官网自己实现了。

The SpringBoot official did not provide the launcher for Mybatis, but the Mybatis network did it itself.

1.在项目的 pom.xml 文件中加入如下依赖:


2. 配置 application.yml ,常用配置如下:


3. 配置Mapper扫描

需要注意,这里没有配置mapper接口扫描包,因此我们需要给每一个Mapper接口添加 @Mapper 注解,才能被识别。

Note that there is no mapper interface scan package configured here, so we need to add @Mapper notes to each Mapper interface in order to be recognised.


或者,我们也可以不加注解,而是在启动类上添加扫描包注解(推荐):

Alternatively, we could add scan packages to the start-up category without comment (recommended by ):


以下代码示例中,我们将采用@MapperScan扫描方式进行。
**

In the following code example, we will do it by scanning @MapperScan.
**

什么是通用mapper?

通用mapper 可以极大的方便开发人员进行ORM,提供极其方便的单表增删改查。
什么是通用mapper,一句话简单说,它就是个辅助mybatis极简单表开发的组件。它不是为了替代mybatis,而是让mybatis的开发更方便。
可以按照自己的需要选择通用方法,还能很方便的开发自己的通用方法。

Universal mappers can make it easier for developers to conduct ORMs and provide extremely convenient list additions and deletions.
What is a universal mapper, in short, is a component to support mybatis' very simple table development. It is not intended to replace mybatis, but to make it easier for mebatis to develop.
can choose a generic method according to its own needs, and it can also facilitate the development of its own generic approach.

为什么要用通用mapper?

原生Mybatis的痛点

1、mapper.xml文件里有大量的sql,当数据库表字段变动,配置文件就要修改
2、需要自己实现sql分页,select * from table where . . . limit 1,3
自己手写分页,除了传参page、pageSize,还需要返回条目总数count。
3、数据库可移植性差:如果项目更换数据库,比如oracle-->mysql,mapper.xml中的sql要重新写,因为Oracle的PLSQL 和mysql 支持的函数是不同的。
4、生成的代码量过大。
5、批量操作,批量插入,批量更新,需要自写。

1. The mapper.xml file contains a large number of sqls.
3; when the field of the database table changes, the configuration file changes
2 and requires self-fulfilling sql subpages, number * from table where.... limit 1,3
of its own handwritten subpages needs to be returned to the total number of entries in addition to page, pageSize.
3; database portability poor: if the project changes the database, for example, oracle-> Mysql, mapper.xml, sql is rewritten because the PLSQL and Mysql support functions are different.
4; the code generated is too large.
5; batch operations; batch insertion; batch update; self-written.

使用通用mapper的步骤

需要导入的jar包

needs to import


编写对应的实体类

prepares the corresponding entity category


编写通用mapper类

Preparation of generic mapper class


在启动类中添加扫描标签

Adds scanning tags to the start-up class


在service类中使用对应的mapper接口

uses the corresponding mapper interface in the service class




导入对应的jar包

Import the corresponding jar bag



编写测试类

Preparation of test class










在这里插入图片描述

 insert

添加项目的pom.xml插件;在pom.xml要显式的加入插件spring-boot-maven-plugin,否则无法产生 jar 清单文件,导致打出来的 jar 无法使用命令运行;

Adds a pom.xml plugin for the item; adds a spring-boot-maven-plugin plugin that is visible in the pom.xml, otherwise the jar list file cannot be generated, resulting in a hit-out jar that cannot run with the command;



使用maven的命令package打包;

(a) Packing with maven's command;

在这里插入图片描述

Page description

之后在项目下的 target 目录中将有如下jar包:
在这里插入图片描述

This will be followed by the following jar packages in the project's target directory:

在这里插入图片描述

Page description

运行打出来的包;使用命令: java –jar 包全名 或者写一个 bat 文件,里面包含 java –jar 包全名;这样就可以双
击启动应用。
如执行上述打出来的jar的命令为:

Run the packed package; use the command: java ~jar package full name or write a bat file containing the full name java ~jar package; so that you can double
click to start the application.
If you execute the above-mentioned jar package, the order is:


在这里插入图片描述

Page description

美化布局示例

欧易(OKX)最新版本

【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   全球官网 大陆官网

币安(Binance)最新版本

币安交易所app【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址

火币HTX最新版本

火币老牌交易所【遇到注册下载问题请加文章最下面的客服微信】永久享受返佣20%手续费!

APP下载   官网地址
文字格式和图片示例

注册有任何问题请添加 微信:MVIP619 拉你进入群

弹窗与图片大小一致 文章转载注明

分享:

扫一扫在手机阅读、分享本文

发表评论
平台列表
美化布局示例

欧易(OKX)

  全球官网 大陆官网

币安(Binance)

  官网

火币(HTX)

  官网

Gate.io

  官网

Bitget

  官网

deepcoin

  官网
热门文章
  • 从 IPFS社区Meetup谈谈2020年的IPFS的发展历程

    从 IPFS社区Meetup谈谈2020年的IPFS的发展历程
    8月3日, IPFS社区Meetup 如期举办,这一次的社区Meetup由交流与演讲和闪电演示两部分组成,其实该会议主要带领我们回顾了IPFS在2020年的发展历程(包括项目进展、IPFS生态发展等),展示了IPFS及其生态。2020年对于IPFS而言是不平凡的一年,其唯一激励层Filecoin的主网即将上线,这让IPFS和Filecoin在全球范围内得到了前所未有的关注,也推动了IPFS的高速发展。接下来,我们一起走进IPFS在20...
  • 超10万人爆仓,比特币跳水,发生了什么

    超10万人爆仓,比特币跳水,发生了什么
    现货比特币ETF上市第二日,数字货币再迎来抛售。比特币一度跌破42000美元/枚,截止1月13日内跌幅超7%,报42562.1美元/枚。The current Bitcoin ETF is on the second day of the market and the digital currency is sold again. Bitcoin fell by over 7% to $4562.1 on 13 January.现货比特币ETF普遍跌6%左右。其中,DEFI跌...
  • 兴业基金调研远光软件、东芯股份

    兴业基金调研远光软件、东芯股份
    根据6月6日公布的公开市场信息和机构研究,世界安全基金会最近对下列两家上市公司进行了一项研究: 1) 光电软件(工程师基金参与公司专项研究) 其中一个亮点是该公司深入参与建造南方网中心和技术平台,导致南网市场在 " 九天 " 平台产品方面取得重大突破;该公司的Won-宇宙大厅已上线,而且,除了Won-宇宙之外,远洋宇宙的应用现已扩大到Won-宇宙发射、Won-宇宙-教师和政党建设-宇宙;该公司的Far-O-Cloud平台已经实现了完全成熟的国家生产,也可以在全国云中运作。...
  • 0.00003374个比特币等于多少人民币/美金

    0.00003374个比特币等于多少人民币/美金
    0.00003374比特币等于多少人民币?根据比特币对人民币的最新汇率,0.00003374比特币等于2.2826 1222美元/16.5261124728人民币。比特币(BTC)美元(USDT)人民币(CNY)0.00003374克洛克-0/22216.5261124728比特币对人民币的最新汇率为:489807.72 CNY(1比特币=489807.72人民币)(1美元=7.24人民币)(0.00003374USDT=0.0002442776 CNY)。汇率更新于2024...
  • $DOG暴涨400%,加密货币或许正在重新定义和计量“价值”

    $DOG暴涨400%,加密货币或许正在重新定义和计量“价值”
    近/克洛克-0/5,Meme币狗?走吗?去哪?那个?MOON($ DOG)连续上涨超过230%,突破前期高点,达到0.0062美元。在同一时期,比特币生态的许多主流L2协议代币下跌了50%以上。这些就是我们所说的“价值币”。虽然大起大落不能说明什么,但从过去的牛市来看,领头羊MemeCoin表现非凡。在上一轮牛市中,$DOGE的价格上涨了超过150倍,其市值接近900亿美元。还有其他MemeCoin,如$Shib、$People、$ELON、$AKITA等。2 vkwmkpm...
标签列表