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.
一般把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: 项目各种配置其实是开发时的损耗, 因为在思考 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. 项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这难题实在太棘手。并且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。 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. 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 的开发者提供一个非常快速的、广泛接受的入门体验 能够使用Spring Boot搭建项目 Can build projects using Spring Boot 需求:可以在浏览器中访问http://localhost:8080/hello输出一串字符 Demand: The default port of 创建一个普通的maven工程 Creates a normal maven project
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) ** ** ** @GetMapping()包含以下注解** ** @GetMapping() contains the following note**
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配置了,我们不妨来回顾一下 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 在此时因为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. 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. 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类和一些注解,比较常用的注解有: 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 目标:可以使用@Value获取配置文件配置项并结合@Bean注册组件到Spring Target: Profile configurations can be obtained using @Value and linked to @Bean's registered component to Spring 分析: Analysis : 添加依赖; Add dependency; 创建数据库; 创建数据库连接参数的配置文件jdbc.properties; creates profile for database connection parametersjdbc.properties; ** **br < strong> creates configuration class; ** ** ** 目标:能够使用@ConfigurationProperties实现Spring Boot配置文件配置项读取和应用 Objective: can read and apply the Spring Boot profile with @ConfigurationProperties 分析: analysis: 实现:可以使用Spring Boot提供的注解@ConfigurationProperties,该注解可以将Spring Boot的配置文件(默认必须为application.properties或application.yml)中的配置项读取到一个对象中。 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). **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配置文件中读取配置项 ConfigurationProperties Read configuration item **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 这个类的对象 Declares the use of objects in the JdbcProperties class 注入方式1 注入方式2 @Autowired注入 @Autowired Injected 注入方式3 构造函数注入 Construct function injection **4. **测试 **4. ** Tests
事实上,如果一段属性只有一个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)! 注意事项: Note: 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
将application.properties配置文件修改为application.yml的话: Change the application.properties profile to application.yml propeties文件 propecies yml文件 yml/strong> 在spring boot中是被允许的。这些配置文件的名称必须为application-***.yml,并且这些配置文件必须要在application.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. 那么这两类配置文件都有效。在两个配置文件中如果存在同名的配置项的话会以properties文件的为主。 Both profiles are valid. If there is a configuration with the same name in both profiles, the profile is dominated by the profile. 语法: key: value Syntax: Key: value 语法: 示例代码 example code 语法: 注意:value1与之间的 - 之间存在一个空格 notes that there is an example of a space between 使用Spring Boot之后,一个整合了SpringMVC的WEB工程开发,变的无比简单,那些繁杂的配置都消失不见了,这是如何做到的? 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?
我们发现特别的地方有两个: We found two special features: 点击进入,查看源码: Click into, view source:
这里重点的注解有3个: highlights three notes:
通过这段我们可以看出,在这个注解上面,又有一个 @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. 关于这个注解,官网上有一段说明: 总结: 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. 我们跟进源码: We follow the source code :
并没有看到什么特殊的地方。我们查看注释: doesn't see anything special. Let's look at the note:
大概的意思: approximation: 传统项目的缺点:
1.复杂的配置
2.一个是混乱的依赖管理
3.而Spring Boot让这一切成为过去!
2.直接嵌入应用服务器,如tomcat、jetty、undertow等;不需要去部署war包
3.提供固定的启动器依赖去简化组件配置;实现开箱即用(启动器starter-其实就是Spring Boot提供的一个jar包),通过自己设置参数(.properties或.yml的配置文件),即可快速使用。
4.自动地配置Spring和其它有需要的第三方依赖
5.提供了一些大型项目中常见的非功能性特性,如内嵌服务器、安全、指标,健康检测、外部化配置等
6.绝对没有代码生成,也无需 XML 配置
2.
strong > 4. Automatic 6.
默认端口为8080
is 8080 , which can be accessed from the browser at http://localhost:8080/ello
1. 创建工程;
2. 添加依赖(启动器依赖,spring-boot-starter-web);
3. 创建启动类;
4. 创建处理器Controller
@RestController包含以下注解
@RestController contains note 5. 测试
Spring的历史:
strong>Sprint: .Spring1.0时代
Spring2.0时代
Spring3.0及以后
@Configuration :声明一个类作为配置类,代替xml文件@Bean :声明在方法上,将方法的返回值加入Bean容器,代替 案例
需求:使用Java代码配置数据库连接池,并可以在处理器中注入并使用
步骤:
steps :
创建配置类;
**
改造处理器类注入数据源并使用
transform processor type injects data sources and uses 案例
**
需求:将配置文件中的配置项读取到一个对象中;
**br>
**
实现步骤:
**
**1. **创建配置项类JdbcProperties类,在该类名上面添加@ConfigurationProperties;
**br>
> **1. ** Create configuration class JdbcProperties with the addition of @ConfutureProperties;
** prefix 表示 配置项的前缀**
** 配置项类中的类变量名必须要与 前缀之后的配置项名称保持 松散绑定(相同)**
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
然后要使用配置的话;可以通过以下方式注入JdbcProperties:
by @EnableConfigurationProperties(JdbcProperties.clas) and then uses configurations; JdbcProperties can be injected by:
方法参数注入
优雅的SpringBoot注入方式
这种读取方式不需要创建对应的类,是直接读取配置文件中以"jdbc"为前缀的项,然后自动的匹配方法中要返回值的属性,把与jdbc中对应后缀的名称与类中对应的属性的名称一致的自动匹配,自动注入
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配置文件:
**
案例
**
比如有两个配置文件application-abc.yml,application-def.yml
br> case
br> such as two configuration-abc.yml, application-def.yml如果properties和yml配置文件同时存在在spring boot项目中:
yml配置普通数据
配置对象数据||配置Map数据
key:
key1: value1
key2: value2
** 或者:**
key: {key1: value1,key2: value2}
Key1: value1
key2: value2
** Or: br> key: {key1: value1, Key2: value2}配置数组(List、Set)数据
key:
key:
或者:
key: [value1,value2]
例子:
: 整合
一切魔力的开始,都是从我们的main函数来的,所以我们再次来看下启动类:
All the magic starts with our main function, so let's look again at the starting class:
注解:@SpringBootApplication
run方法:SpringApplication.run()我们分别来研究这两个部分
notes: @SprintBootApplication
run Method: SpringApplication.run() We're looking at each of these two parts.
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
@SpringBootConfuture
@EnableAutoConfuture
@ComponentScan@SpringBootConfiguration
@EnableAutoConfiguration
第二级的注解 @EnableAutoConfiguration ,告诉Spring Boot基于你所添加的依赖,去“猜测”你想要如何配置Spring。比如我们引入了 spring-boot-starter-web ,而这个启动器中帮我们添加了 tomcat 、 SpringMVC的依赖。此时自动配置就知道你是要开发一个web应用,所以就帮你完成了web及SpringMVC的默认配置了!
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!@ComponentScan
配置组件扫描的指令。提供了类似与 context:component-scan 标签的作用
通过basePackageClasses或者basePackages属性来指定要扫描的包。如果没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包
而我们的@SpringBootApplication注解声明的类就是main函数所在的启动类,因此扫描的包是该类所在包及其子包。因此,一般启动类会放在一个比较前的包目录中
, 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类构建的时候,有这样一段初始化代码:
跟进去:
这里发现会通过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:
可以发现,其地址是: 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: **以后我们引入的任何第三方启动器,只要实现自动配置,也都会有类似 ** ** Any third-party starter that we'll introduce later, as long as it's automatically configured, will be similar ** 我们打开刚才的spring.factories文件: 可以发现以EnableAutoConfiguration接口为key的一系列配置,key所对应的值,就是所有的自动配置类,可以在当前的jar包中找到这些自动配置类: 非常多,几乎涵盖了现在主流的开源框架,例如: contains a large number of open source frameworks that cover almost all of the current mainstream, e.g.: redis **
我们看到这个类上的4个注解: We see four notes on this category:
redis
jms
amqp
jdbc
jackson
mongodb
jpa
solr
elasticsearch
... 等等
我们来看一个我们熟悉的,例如SpringMVC,查看mvc 的自动配置类:
**
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>, 打开WebMvcAutoConfiguration:
**@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的类,那么这个默认配置就会失效!
接着,我们查看该类中定义了什么:
**
**@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
视图解析器:
处理器适配器(HandlerAdapter):
还有很多,这里就不一一截图了。
There's more. There's not a single picture here.
另外,这些默认配置的属性来自哪里呢?
And where are the properties of these default configurations?
我们看到,这里通过@EnableAutoConfiguration注解引入了两个属性:WebMvcProperties和ResourceProperties。这不正是SpringBoot的属性注入玩法嘛。
我们查看这两个属性类:
We look at these two properties:
**如果我们要覆盖这些默认属性,只需要在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:
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
步骤二
在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.
@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方法时,会把此前缀去掉
@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.
附带一个我使用的例子
注册有任何问题请添加 微信:MVIP619 拉你进入群
打开微信扫一扫
添加客服
进入交流群
发表评论