Spring-boot特性笔记
Spring Boot
1. Spring Boot 介绍
Spring Boot helps you to create stand-alone, production-grade Spring-based Applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
You can use Spring Boot to create Java applications that can be started by using java -jar
or more traditional war
deployments. We also provide a command line tool that runs “spring scripts”.
- Provide a radically faster and widely accessible getting-started experience for all Spring development.
- Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
- Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).
- Absolutely no code generation and no requirement for XML configuration.
1.1 Quick Start Hello world
Spring boot 在各个平台都有涉猎,我们这里使用maven 插件 + java1.8环境 + idea IDE
进行配置快速“hello,world”
-
使用 Spring 官方提供的
https://start.spring.io/
快速构建maven环境 -
复制下来添加到 idea 的maven 项目中的pom文件里,这里由于阿里云镜像库里没有maven-plugin所以这里的打包插件问题我们暂时忽略
<modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> </parent> <groupId>com.wmk</groupId> <artifactId>bootTest</artifactId> <version>0.0.1-SNAPSHOT</version> <name>bootTest</name> <description>springboot quickstart</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
-
编写一个主程序(Spring Boot应用启动类)
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
-
编写相关的Controller
@RestController public class HelloController { @RequestMapping("/hello") public String hello(){ return "Hello World!"; } }
-
运行启动类测试
1.2 Starter
Spring Boot拥有很多方便使用的starter(Spring提供的starter命名规范spring-boot-starter-xxx.jar,第三方提供的starter命名规范xxx-spring-boot-starter.jar
),比如spring-boot-starter-log4j
、mybatis-spring-boot-starter.jar
等,各自都代表了一个相对完整的功能模块。
SpringBoot-starter是一个集成接合器,完成两件事:
- 引入模块所需的相关jar包
- 自动配置各自模块所需的属性
具体实现原理见 源码阅读 Spring-boot-starter 实现原理
Spring Boot在该org.springframework.boot
组下提供了以下应用程序启动器:
名称 | 描述 |
---|---|
spring-boot-starter |
核心入门工具,包括自动配置支持,日志记录和YAML |
spring-boot-starter-activemq |
使用Apache ActiveMQ的JMS消息传递入门 |
spring-boot-starter-amqp |
使用Spring AMQP和Rabbit MQ的入门 |
spring-boot-starter-aop |
使用Spring AOP和AspectJ进行面向方面编程的入门 |
spring-boot-starter-artemis |
使用Apache Artemis的JMS消息传递入门 |
spring-boot-starter-batch |
使用Spring Batch的入门 |
spring-boot-starter-cache |
使用Spring Framework的缓存支持的入门者 |
spring-boot-starter-data-cassandra |
使用Cassandra分布式数据库和Spring Data Cassandra的入门 |
spring-boot-starter-data-cassandra-reactive |
使用Cassandra分布式数据库和Spring Data Cassandra Reactive的入门 |
spring-boot-starter-data-couchbase |
使用Couchbase面向文档的数据库和Spring Data Couchbase的入门 |
spring-boot-starter-data-couchbase-reactive |
使用Couchbase面向文档的数据库和Spring Data Couchbase Reactive的入门 |
spring-boot-starter-data-elasticsearch |
使用Elasticsearch搜索和分析引擎以及Spring Data Elasticsearch的入门者 |
spring-boot-starter-data-jdbc |
使用Spring Data JDBC的入门 |
spring-boot-starter-data-jpa |
将Spring Data JPA与Hibernate结合使用的入门 |
spring-boot-starter-data-ldap |
使用Spring Data LDAP的入门 |
spring-boot-starter-data-mongodb |
使用MongoDB面向文档的数据库和Spring Data MongoDB的入门 |
spring-boot-starter-data-mongodb-reactive |
使用MongoDB面向文档的数据库和Spring Data MongoDB Reactive的入门 |
spring-boot-starter-data-neo4j |
使用Neo4j图形数据库和Spring Data Neo4j的入门 |
spring-boot-starter-data-r2dbc |
使用Spring Data R2DBC的入门 |
spring-boot-starter-data-redis |
使用Redis键值数据存储与Spring Data Redis和Lettuce客户端的入门 |
spring-boot-starter-data-redis-reactive |
将Redis键值数据存储与Spring Data Redis Reacting和Lettuce客户端一起使用的入门 |
spring-boot-starter-data-rest |
使用Spring Data REST在REST上公开Spring Data存储库的入门 |
spring-boot-starter-data-solr |
结合使用Apache Solr搜索平台和Spring Data Solr的入门者 |
spring-boot-starter-freemarker |
使用FreeMarker视图构建MVC Web应用程序的入门 |
spring-boot-starter-groovy-templates |
使用Groovy模板视图构建MVC Web应用程序的入门 |
spring-boot-starter-hateoas |
使用Spring MVC和Spring HATEOAS构建基于超媒体的RESTful Web应用程序的入门者 |
spring-boot-starter-integration |
使用Spring Integration的入门 |
spring-boot-starter-jdbc |
结合使用JDBC和HikariCP连接池的入门 |
spring-boot-starter-jersey |
使用JAX-RS和Jersey构建RESTful Web应用程序的入门。的替代品spring-boot-starter-web
|
spring-boot-starter-jooq |
使用jOOQ访问SQL数据库的入门。替代[spring-boot-starter-data-jpa ]或[spring-boot-starter-jdbc
|
spring-boot-starter-json |
读写JSON入门 |
spring-boot-starter-jta-atomikos |
使用Atomikos的JTA交易入门 |
spring-boot-starter-jta-bitronix |
使用Bitronix的JTA交易入门。自2.3.0起不推荐使用 |
spring-boot-starter-mail |
开始使用Java Mail和Spring Framework的电子邮件发送支持 |
spring-boot-starter-mustache |
使用Mustache视图构建Web应用程序的入门 |
spring-boot-starter-oauth2-client |
使用Spring Security的OAuth2 / OpenID Connect客户端功能的入门 |
spring-boot-starter-oauth2-resource-server |
使用Spring Security的OAuth2资源服务器功能的入门 |
spring-boot-starter-quartz |
入门使用Quartz Scheduler |
spring-boot-starter-rsocket |
用于构建RSocket客户端和服务器的入门 |
spring-boot-starter-security |
使用Spring Security的入门 |
spring-boot-starter-test |
用于使用包括JUnit Jupiter,Hamcrest和Mockito在内的库测试Spring Boot应用程序的入门程序 |
spring-boot-starter-thymeleaf |
使用Thymeleaf视图构建MVC Web应用程序的入门 |
spring-boot-starter-validation |
通过Hibernate Validator使用Java Bean验证的入门 |
spring-boot-starter-web |
使用Spring MVC构建Web(包括RESTful)应用程序的入门者。使用Tomcat作为默认的嵌入式容器 |
spring-boot-starter-web-services |
使用Spring Web Services的入门 |
spring-boot-starter-webflux |
使用Spring Framework的Reactive Web支持构建WebFlux应用程序的入门者 |
spring-boot-starter-websocket |
使用Spring Framework的WebSocket支持构建WebSocket应用程序的入门 |
除了应用程序启动程序,以下启动程序可用于添加生产就绪
功能:
名称 | 描述 |
---|---|
spring-boot-starter-actuator |
使用Spring Boot的Actuator的入门程序,它提供了生产就绪功能,可帮助您监视和管理应用程序 |
最后,Spring Boot还包括以下启动程序,如果您要排除或交换特定的技术方面,可以使用这些启动程序:
名称 | 描述 |
---|---|
spring-boot-starter-jetty |
使用Jetty作为嵌入式servlet容器的入门者。的替代品spring-boot-starter-tomcat
|
spring-boot-starter-log4j2 |
使用Log4j2进行日志记录的启动程序。的替代品spring-boot-starter-logging
|
spring-boot-starter-logging |
使用Logback进行日志记录的启动器。默认记录启动器 |
spring-boot-starter-reactor-netty |
使用Reactor Netty作为嵌入式反应式HTTP服务器的入门者。 |
spring-boot-starter-tomcat |
入门,用于将Tomcat用作嵌入式servlet容器。默认使用的servlet容器启动器spring-boot-starter-web
|
spring-boot-starter-undertow |
使用Undertow作为嵌入式servlet容器的入门。的替代品spring-boot-starter-tomcat
|
1.3 典型代码层次布局
com
+- example
+- myapplication
+- Application.java
|
+- customer
| +- Customer.java
| +- CustomerController.java
| +- CustomerService.java
| +- CustomerRepository.java
|
+- order
+- Order.java
+- OrderController.java
+- OrderService.java
+- OrderRepository.java
1.4 配置Springboot环境
Spring Boot支持基于Java的配置。尽管可以SpringApplication
与XML配置一起使用,但是通常建议主要使用@Configuration
类来进行配置。
1.4.1 导入其他配置类
无需将所有内容使用@Configuration
放在一个类中。所述@Import
注释可以用于导入额外的配置类。另外,可以@ComponentScan
用来自动拾取所有Spring组件,包括@Configuration
类。
1.4.2 导入XML配置
如果绝对必须使用基于XML的配置,建议仍然从一个@Configuration
类开始。然后,可以使用@ImportResource
批注来加载XML配置文件。
1.4.3 自动配置
Spring Boot自动配置会尝试根据添加的jar依赖项自动配置Spring应用程序。例如,如果HSQLDB
在类路径上,并且尚未手动配置任何数据库连接bean,那么Spring Boot会自动配置内存数据库。
需要通过将@EnableAutoConfiguration
或@SpringBootApplication
注释添加到一个@Configuration
类中来选择自动配置。(只能添加一个@SpringBootApplication
或@EnableAutoConfiguration
注释。通常建议您仅将一个或另一个添加到@Configuration
Class上)
1.4.4 取代自动配置
自动配置是非侵入性的。在任何时候,都可以开始定义自己的配置,用来替换自动配置的特定部分。例如,如果添加自己的DataSource
bean,则默认的嵌入式数据库支持将退出。
1.4.5 禁用特定的自动配置类
如果发现正在应用不需要的特定自动配置类,则可以使用exclude属性@SpringBootApplication
来禁用它们,如以下示例所示:
import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
public class MyApplication {
}
如果该类不在类路径中,则可以使用excludeName
注释的属性,并指定完全限定的名称。如果您更喜欢使用@EnableAutoConfiguration
而不是@SpringBootApplication
,exclude
并且excludeName
也可以使用。最后,还可以使用spring.autoconfigure.exclude
属性在yml中来控制要排除的自动配置类的列表。
1.5 Spring Beans 及 依赖注入
可以*使用任何标准的Spring Framework技术来定义bean及其注入的依赖。例如:使用@ComponentScan
(查找的bean)和使用@Autowired
(进行构造函数注入)。
如果按照上面的建议构造代码(将应用程序类放在根包中),则可以添加@ComponentScan
而无需任何参数。所有应用程序组件(加了@Component
,@Service
,@Repository
,@Controller
等注解的类)自动注册为Spring bean。
以下示例显示了一个@Service
使用构造函数注入来获取所需RiskAssessor
Bean的Bean:
如果bean具有一个构造函数,则可以省略@Autowired:
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class DatabaseAccountService implements AccountService {
private final RiskAssessor riskAssessor;
@Autowired //如果bean具有一个构造函数,则可以省略@Autowired:
public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}
// ...
}
1.6 @SpringBootApplication注解
单个@SpringBootApplication
注释可用于启用这三个功能,即:
-
@EnableAutoConfiguration
:启用Spring Boot的自动配置机制 -
@ComponentScan
:启用@Component
对应用程序所在的软件包的扫描 -
@Configuration
:允许在上下文中注册额外的bean或导入其他配置类
@SpringBootApplication
还提供了别名定制的属性@EnableAutoConfiguration
和@ComponentScan
。
这些功能都不是强制性的,您可以选择用它启用的任何功能替换此单个注释。例如,您可能不想在应用程序中使用组件扫描或配置属性扫描:
package com.example.myapplication;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
@Import({ MyConfig.class, MyAnotherConfig.class })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
在此示例中,Application
与其他任何Spring Boot应用程序一样,除了不会自动检测@Component-annotated
类和@ConfigurationProperties-annotated
类,并且显式导入用户定义的Bean。
2. Spring Boot 功能
2.1 SpringApplication
本SpringApplication
类提供了一个方便的方式来引导该从开始Spring应用程序main()
的方法。在许多情况下,可以委托给静态SpringApplication.run
方法,如以下示例所示:
public static void main(String[] args) {
SpringApplication.run(MySpringConfiguration.class, args);
}
当应用程序启动时,可以看到类似于以下输出的内容:
默认情况下,会显示INFO
日志消息,包括一些相关的启动详细信息,例如启动应用程序的用户。如果需要除此以外的其他日志级别INFO
,则可以按日志级别中所述(见下文日志级别)进行设置。使用主应用程序类包中的实现版本来确定应用程序版本。设置spring.main.log-startup-info
为可以关闭启动信息记录false
。这还将关闭应用程序活动配置文件的日志记录。
要在启动期间添加其他日志记录,可以logStartupInfo(boolean)
所在的子类中覆盖SpringApplication
。
2.2 启动失败
如果应用程序无法启动,则注册FailureAnalyzers
后将有机会提供专门的错误消息和解决该问题的具体措施。
例如,如果在端口上启动Web应用程序8080
并且该端口已在使用中,则应该看到类似于以下消息的内容:
***************************
APPLICATION FAILED TO START
***************************
Description:
Embedded servlet container failed to start. Port 8080 was already in use.
Action:
Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.
Spring Boot提供了许多FailureAnalyzer
实现,可以自定义实现内容。
2.3 延迟初始化
SpringApplication
允许延迟地初始化应用程序。启用惰性初始化后,将根据需要创建bean,而不是在应用程序启动期间创建bean。因此,启用延迟初始化可以减少应用程序启动所花费的时间。在Web应用程序中,启用延迟初始化将导致许多与Web相关的Bean直到收到HTTP请求后才被初始化。
延迟初始化的缺点是,它可能会延迟发现应用程序问题的时间。如果错误配置的Bean延迟初始化,则启动期间将不再发生故障,并且只有在初始化Bean时问题才会变得明显。还必须注意确保JVM
具有足够的内存来容纳所有应用程序的bean,而不仅仅是启动期间初始化的bean。由于这些原因,默认情况下默认不启用延迟初始化,因此建议在启用延迟初始化之前先对JVM
的堆大小进行微调。
可以使用lazyInitialization
方法在SpringApplicationBuilder
上启动延迟初始化或使用setLazyInitialization
方法以编程方式启用延迟初始化SpringApplication
。另外,还可以使用spring.main.lazy-initialization
以下示例中所示的属性来启用它
spring.main.lazy-initialization=true
如果要禁用应用程序的某些bean的延迟初始化,则可以使用@Lazy(false)
注解将它们的延迟属性显式设置为false 。
2.4 自定义启动横幅
可以通过将banner.txt
文件添加到类路径或将spring.banner.location
属性设置为此文件的位置来更改启动时控制台打印的横幅。如果文件的编码不是UTF-8,则可以设置spring.banner.charset
。除了一个文本文件,你还可以添加一个banner.gif
,banner.jpg
或banner.png
图像文件到类路径或设置spring.banner.image.location
属性。图像将转换为ASCII艺术作品并打印在任何文字横幅上方。
在banner.txt
文件内部,可以使用以下任意占位符:
表1.标语变量 | |
---|---|
变量 | 描述 |
${application.version} | 您的应用程序的版本号,如中所述MANIFEST.MF。例如,Implementation-Version: 1.0打印为1.0。 |
${application.formatted-version} | 您的应用程序的版本号,已声明MANIFEST.MF并进行了格式显示(用括号括起来,并带有前缀v)。例如(v1.0)。 |
${spring-boot.version} | 您正在使用的Spring Boot版本。例如2.4.0。 |
${spring-boot.formatted-version} | 您正在使用的Spring Boot版本,其格式进行了显示(用方括号括起来,并带有前缀v)。例如(v2.4.0)。 |
A n s i . N A M E ( 或 {Ansi.NAME}(或 Ansi.NAME(或{AnsiColor.NAME}, A n s i B a c k g r o u n d . N A M E , {AnsiBackground.NAME}, AnsiBackground.NAME,{AnsiStyle.NAME}) | NAMEANSI转义代码的名称在哪里。有关AnsiPropertySource详细信息,请参见。 |
${application.title} | 您的应用程序的标题,如中所述MANIFEST.MF。例如Implementation-Title: MyApp打印为MyApp。 |
2.5 自定义SpringApplication
如果SpringApplication
默认设置不符合您的喜好,则可以创建一个本地实例并对其进行自定义。例如,要关闭横幅,您可以编写:
public static void main(String[] args) {
/*传递给构造函数的参数SpringApplication是Spring bean的配置源。在大多数情况下,它们是对带有 @Configuration的注解的类的引用,但也可以是对XML配置或应扫描的程序包的引用。*/
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
也可以SpringApplication
通过使用application.properties
文件来配置。有关详细信息,请参见外部化配置(见下文)。
有关配置选项的完整列表,请参见SpringApplication Javadoc
。
2.6 外部化配置*
Spring Boot可以外部化配置,以便可以在不同环境中使用相同的应用程序代码。可以使用各种外部配置源,包括Java属性文件,YAML文件,环境变量和命令行参数。属性值可以直接注射到你的bean@Value
注释,通过Spring的访问Environment
,或者通过@ConfigurationProperties
绑定到结构化对象。
2.6.1 PropertySource 顺序
Spring Boot使用一个非常特殊的PropertySource
顺序,该顺序旨在允许合理地覆盖值。按以下顺序考虑属性(较低项的值覆盖较早项的值):
- 默认属性(通过设置指定
SpringApplication.setDefaultProperties
)。 - 在
@Configuration
类上的@PropertySource
注解。注意,Environment
在刷新应用程序上下文之前,不会将此类属性源添加到其中。现在如果配置某些属性(如logging.*
和spring.main.*
在刷新开始之前已经读取)为时已晚。 - 配置数据(例如
application.properties
文件) - 一个
RandomValuePropertySource
,只在random.*中有配置。 - 操作系统环境变量。
- Java系统属性(
System.getProperties()
)。 - 来自的JNDI属性
java:comp/env
。 -
ServletContext
初始化参数。 -
ServletConfig
初始化参数。 - 来自的属性
SPRING_APPLICATION_JSON
(嵌入在环境变量或系统属性中的嵌入式JSON)。 - 命令行参数。
-
properties
测试中的属性。可用于测试应用程序的特定部分的@SpringBootTest的测试注解。 -
@TestPropertySource
测试中的注解。 -
$HOME/.config/spring-boot
当devtools处于活动状态时,目录中的Devtools全局设置属性。
2.6.2 Springboot外部配置加载顺序
Springboot外部配置加载顺序如下,优先级从高到底,并且高优先级的配置覆盖底优先级的配置形成互补配置
-
命令行参数比如:java -jar xxxx.jar --server.port=8087 --server.context-path=/show 多个配置中间用空格分开
由jar包外向jar包内进行加载,比如和工程平级目录下面的配置文件优先级高于jar包内部的配置文件
优先加载带profile
- jar包外部的application-{profile}.propertie或application.yml(带spring.profile)配置文件
- jar包内部的application-{profile}.propertie或application.yml(带spring.profile)配置文件再来加载不带profile
- jar包外部的application.propertie或application.yml(不带spring.profile)配置文件
- jar包内部的application.propertie或application.yml(不带spring.profile)配置文件
在应用程序类路径上(例如,在jar内),您可以使用一个application.properties
文件,该文件为提供合理的默认属性值name
。在新环境中运行时,application.properties
可以在jar外部提供一个文件,该文件将覆盖name
。对于一次性测试,可以使用特定的命令行开关(例如,java -jar app.jar --name="Spring"
)启动。
2.6.4 访问命令行属性
默认情况下,SpringApplication
将任何命令行选项参数(即以开头的参数--
,例如--server.port=9000
)转换为一个配置并将其添加到Spring Environment
。如前所述,命令行属性始终优先于基于文件提供的属性。
如果不希望将命令行属性添加到中Spring Environment
,则可以使用禁用它们SpringApplication.setAddCommandLineProperties(false)
。
2.6.5 外部配置文件读取
application.properties是spring boot默认的配置文件,如果在不同的目录中存在多个配置文件,它的读取顺序是:
-
config/application.properties(项目根目录中config目录下)
-
config/application.yml
-
application.properties(项目根目录下)
-
application.yml
-
resources/config/application.properties(项目resources目录中config目录下)
-
resources/config/application.yml
-
resources/application.properties(项目的resources目录下)
-
resources/application.yml
2.6.6 @ConfigurationProperties 注解
@ConfigurationProperties支持松散绑定。@ConfigurationProperties(prefix = “person”),只需要指定一个前缀,就能绑定有这个前缀的所有属性值。
@ConfigurationProperties 的基本用法非常简单:我们为每个要捕获的外部属性提供一个带有字段的类。请注意以下几点:
- 前缀定义了哪些外部属性将绑定到类的字段上
- 根据 Spring Boot 宽松的绑定规则,类的属性名称必须与外部属性的名称匹配
- 我们可以简单地用一个值初始化一个字段来定义一个默认值
- 类本身可以是包私有的
- 类的字段必须有公共 setter 方法
用法:只要在外部配置文件中根据指定的前缀进行配置,就可以获取到外部文件的属性值。
2.6.7 @value 注解
@value 注解也是用来赋值的一个注解,和@ConfigurationProperties 注解区别如下:
@ConfigurationProperties | @value | |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定(松散语法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型封装 | 支持 | 不支持 |
2.7 Profiles
为了解决不同环境需要的配置切换问题,Spring Profiles 提供了一种方式允许我们指定在特定环境下只加载对应的程序配置,每一种环境配置对应一个 Profile,只有当前 Profile 处于**状态时,才会将该 Profile 所对应的配置和 Bean 加载到 Spring 程序中。
Spring Profiles 就是针对应用程序,不同环境需要不同配置加载的一种解决方案。
当然 Spring 允许多个 Profile 处于**状态,比如将应用配置进行细分成数据库配置,消息中间件配置,缓存配置等,都为各自在不同环境定义不同的 Profile 名称,在需要**环境对应配置时,指定多个 Profile。
2.7.1 使用@Profile注解
@profile
注解的作用是指定类或方法在特定的 Profile 环境生效,任何@Component
或@Configuration
注解的类都可以使用@Profile
注解。在使用DI来依赖注入的时候,能够根据@profile
标明的环境,将注入符合当前运行环境的相应的bean。
使用要求:
-
@Component
或@Configuration
注解的类可以使用@profile
-
@Profile
中需要指定一个字符串,约定生效的环境 -
可以作用与类、方法以及注解上
2.7.2 配置文件使用profile环境
1. properties 配置
假设,一个应用的工作环境有:dev、test、prod
那么,我们可以添加 4 个配置文件:
-
applcation.properties
- 公共配置 -
application-dev.properties
- 开发环境配置 -
application-test.properties
- 测试环境配置 -
application-prod.properties
- 生产环境配置
在 applcation.properties
文件中可以通过以下配置来** profile:
spring.profiles.active = test
2. yml 配置
与 properties 文件类似,我们也可以添加 4 个配置文件:
-
applcation.yml
- 公共配置 -
application-dev.yml
- 开发环境配置 -
application-test.yml
- 测试环境配置 -
application-prod.yml
- 生产环境配置
在 applcation.yml
文件中可以通过以下配置来** profile:
spring:
profiles:
active: prod
此外,yml 文件也可以在一个文件中完成所有 profile 的配置:
# ** prod
spring:
profiles:
active: prod
# 也可以同时**多个 profile
# spring.profiles.active: prod,proddb,prodlog
---
# dev 配置
spring:
profiles: dev
# 略去配置
---
spring:
profiles: test
# 略去配置
---
spring.profiles: prod
spring.profiles.include:
- proddb
- prodlog
---
spring:
profiles: proddb
# 略去配置
---
spring:
profiles: prodlog
# 略去配置
注意:不同 profile 之间通过 ---
分割
2.7.3 Profile**
1. 配置文件方式**profile
确定当前使用的是哪个环境,这边环境的值与application-prod.properties中-后面的值对应,这是SpringBoot约定好的。
在resources/application.properties中添加下面的配置。需要注意的是,spring.profiles.active的取值应该与@Profile
注解中的标示保持一致。
spring.profiles.active=dev
除此之外,同理还可以在resources/application.yml中配置,效果是一样的:
spring:
profiles:
active: dev
2. 命令行方式**profile
在打包后运行的时候,添加参数:
java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev;
2.7.4 Profile组
有时可能需要**多个Profile,则使用profile组进行配置
properties:
spring.profiles.group.production[0]=proddb
spring.profiles.group.production[1]=prodmq
yml:
spring:
profiles:
group:
production:
- "proddb"
- "prodmq"
启动时配置:
spring.profiles.active=production