一、SpirngBoot项目默认的配置文件application.properties
当你创建一个新的 Spring Boot 项目后,在sources目录下会有一个默认的配置文件是 application.properties
application.properties 文件是 Spring Boot 项目中常用的配置文件之一,常用于配置项目的各类属性。这里列出一些常见的配置示例,涵盖数据库、日志、端口、国际化等方面。
1. 服务器端口配置
server.port=8081
默认情况下,Spring Boot 应用运行在 8080 端口上。通过该配置可以更改为其他端口。
2. 日志级别配置
logging.level.root=INFO
logging.level.com.example=DEBUG
root 表示全局的日志级别,com.example 表示包级别的日志级别。
3. 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
这是 MySQL 数据库的连接配置,url 中指定了数据库的地址和数据库名称,username 和 password 对应数据库的用户名和密码。
4. JPA 和 Hibernate 配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
5. 文件上传配置
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=10MB
6. 国际化配置
spring.messages.basename=messages
spring.messages.encoding=UTF-8
7. Actuator 配置
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
8. Session 配置
server.servlet.session.timeout=30m
9. Spring Boot Banner 关闭
spring.main.banner-mode=off
启动 Spring Boot 应用时,关闭控制台上的 Banner 显示。
10. CORS 配置
spring.mvc.cors.allowed-origins=http://localhost:3000
spring.mvc.cors.allowed-methods=GET,POST
11. 自定义配置
Spring Boot 允许在 application.properties 中自定义配置,通常可以定义一些自定义的属性,供应用中使用:
myapp.feature.enabled=true
myapp.api.url=https://api.example.com
@Value("${myapp.feature.enabled}")
private boolean featureEnabled;
@Value("${myapp.api.url}")
private String apiUrl;
12. 邮件配置
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=myemail@example.com
spring.mail.password=mypassword
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
13. Redis 配置
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=mypassword
14. 自定义错误页面路径
server.error.path=/error
15. 启用 HTTPS
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=yourpassword
server.ssl.keyStoreType=PKCS12
server.ssl.keyAlias=tomcat
这些都是 application.properties 中常用的一些配置示例。根据项目需求,可以在 application.properties 文件中进行各种功能模块的配置。
二、将application.properties文件转换为application.yml文件
.yml 文件的全称是 YAML Ain't Markup Language,与 .yaml 文件相同。.yml 只是 .yaml 的缩写,两者在使用上是等价的,没有功能或语法上的区别。通常,YAML 文件的扩展名可以是 .yaml 或 .yml,选择哪个主要取决于个人习惯或项目约定。
YAML 是一种简洁的、可读性高的用于数据序列化的语言,广泛用于配置文件中,比如在 Docker、Kubernetes、Spring Boot 等项目中。
YAML 格式的配置文件相比于传统的 application.properties 文件更加简洁易读,支持层次化结构。该文件可以用来配置各种属性。
在 Spring Boot 项目中,application.yml 文件的默认位置是 src/main/resources,但你可以通过在 pom.xml 文件中配置插件或属性来指定 application.yml 文件的自定义位置。
下面介绍两种方法:一种是通过 pom.xml 中的 build 插件来将配置文件复制到指定位置,另一种是通过设置环境参数来指定 application.yml 的位置。
方法 1:通过 pom.xml 中的 maven-resources-plugin 插件复制配置文件
如果你希望在打包时,将 application.yml 文件复制到指定目录下,可以使用 maven-resources-plugin 插件来配置 application.yml 文件的输出目录。
示例 1:将 application.yml 复制到 config/ 目录
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/config</outputDirectory> <!-- 指定输出目录 -->
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>application.yml</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
在这个示例中,maven-resources-plugin 插件会在 process-resources 阶段将 application.yml 文件复制到 target/config 目录下。你可以根据项目需求修改 outputDirectory 以设置文件的最终输出路径。
示例 2:将 application.yml 复制到自定义的外部目录
如果你想把 application.yml 文件复制到项目目录之外的某个外部目录,可以修改 outputDirectory。
<outputDirectory>/path/to/external/config</outputDirectory>
这个配置会将 application.yml 文件复制到 /path/to/external/config 目录下。
方法 2:通过 spring.config.location 指定配置文件位置
如果你不想复制文件,而是直接指定 application.yml 文件的位置,你可以通过 spring.config.location 参数在 pom.xml 中配置 application.yml 文件的路径。这可以通过在 pom.xml 中添加 maven-surefire-plugin 插件来实现。
示例:通过 maven-surefire-plugin 传递 spring.config.location 参数
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<systemPropertyVariables>
<!-- 设置 application.yml 文件的自定义位置 -->
<spring.config.location>file:/path/to/your/application.yml</spring.config.location>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
在这个例子中,maven-surefire-plugin 插件会在测试阶段运行时将 spring.config.location 参数传递给 Spring Boot,告诉它从 /path/to/your/application.yml 加载配置文件。
同样,你也可以通过以下方式启动应用程序来指定配置文件的路径:
mvn spring-boot:run -Dspring.config.location=file:/path/to/your/application.yml
方法 3:通过 spring-boot-maven-plugin 传递配置文件路径
你还可以通过 spring-boot-maven-plugin 在打包或运行时指定 application.yml 文件的位置。
示例:通过 spring-boot-maven-plugin 传递配置文件路径
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<jvmArguments>
-Dspring.config.location=file:/path/to/your/application.yml
</jvmArguments>
</configuration>
</plugin>
</plugins>
</build>
在这个配置中,spring-boot-maven-plugin 会在启动时通过 JVM 参数传递 spring.config.location,指定自定义的 application.yml 文件路径。
总结
- maven-resources-plugin 复制 application.yml 文件到指定目录。
- spring.config.location 参数在 maven-surefire-plugin 或 spring-boot-maven-plugin 中指定配置文件的位置。
选择合适的方式取决于你的项目需求。如果你想要外部配置文件的灵活性,可以使用 spring.config.location 参数。如果你需要在构建时自动复制配置文件,则可以使用 maven-resources-plugin 插件。
三、怎么知道application.yml文件中的属性有哪些
在 application.yml 文件中配置属性时,你需要知道要配置的具体功能或模块,然后根据需求使用相应的属性。属性的内容可以通过以下几个途径来了解和填写:
1. Spring Boot 官方文档
Spring Boot 的官方文档提供了大量默认的配置属性。你可以根据你使用的功能模块查找对应的配置属性。例如,配置数据库连接、Web 服务器设置、日志级别等。
2. IDE 自动补全功能
使用 IntelliJ IDEA、Eclipse 等开发工具时,编辑 application.yml 文件时,IDE 通常会提供代码自动补全功能。在输入属性名称时,IDE 会根据上下文和常见的属性提供建议并展示相关的注释。
3. Spring Boot 提供的默认属性
Spring Boot 有许多自动配置的属性,可以不用手动配置,而使用框架的默认设置。你可以查阅这些默认配置,如果需要不同的行为,再通过 application.yml 自定义覆盖这些默认值。
4. 第三方库的文档
如果你的项目集成了第三方库(如数据库、消息队列、缓存等),这些库往往有自己专属的配置属性。这些属性通常会在该库的官方文档中列出。例如MySQL数据库的配置
5. Spring Boot Actuator 的 /actuator/configprops 端点
如果你启用了 Spring Boot Actuator,Actuator 提供了一个有用的端点 /actuator/configprops,它展示了应用中所有配置属性的当前值。这对于了解哪些属性正在被使用以及它们的值非常有用。
- Actuator,确保配置了 /actuator/configprops 端点。
- http://localhost:8080/actuator/configprops 查看当前应用中的配置属性及其值。
6. 查看依赖包中的默认配置
Spring Boot 的很多功能会根据依赖自动配置,比如数据库连接、消息中间件、缓存等。你可以查看项目中引入的依赖的 spring-configuration-metadata.json 文件,这个文件包含了很多可以配置的属性。
7. 从示例项目学习
如果你不确定某个模块的配置属性,查看类似功能的开源项目或教程也能帮助你理解应该在 application.yml 文件中写什么。很多情况下,你可以通过参考 Spring Boot 社区中的示例项目,找到所需的配置。
四、在项目中如何获取application.yml文件中的属性
在 Spring Boot 项目中,可以通过多种方式获取 application.yml 文件中的配置信息。最常见的方法有以下几种:
1. 使用 @Value 注解
@Value 注解可以用于直接注入 application.yml 文件中的属性值到类的字段或方法参数中。
name: MyApp
version: 1.0
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyAppConfig {
@Value("${myapp.name}")
private String appName;
@Value("${myapp.version}")
private String appVersion;
public void printConfig() {
System.out.println("App Name: " + appName);
System.out.println("App Version: " + appVersion);
}
}
在上述示例中,@Value("${myapp.name}") 获取 application.yml 中的 myapp.name 属性值,并将其赋值给 appName 字段。
2. 使用 @ConfigurationProperties 注解
如果有多个相关配置项,建议使用 @ConfigurationProperties 来批量获取配置。这种方式更加灵活,适合处理多级属性结构。
name: MyApp
version: 1.0
author:
name: John Doe
email: johndoe@example.com
可以通过创建一个专门的配置类,使用 @ConfigurationProperties 注解来获取:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private String version;
private Author author;
public static class Author {
private String name;
private String email;
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}
使用 @EnableConfigurationProperties 注解启用配置类(通常在 @SpringBootApplication 注解类中):
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(MyAppProperties.class)
public class MyAppApplication {
public static void main(String[] args) {
SpringApplication.run(MyAppApplication.class, args);
}
}
Environment 接口可以在运行时动态获取属性。适合在某些需要动态获取属性的场景中使用。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class MyAppConfig {
@Autowired
private Environment env;
public void printConfig() {
String appName = env.getProperty("myapp.name");
String appVersion = env.getProperty("myapp.version");
System.out.println("App Name: " + appName);
System.out.println("App Version: " + appVersion);
}
}
如果你想要从自定义的配置文件中读取属性(如非默认的 application.yml 文件),可以使用 @PropertySource 注解。
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:custom.yml")
public class CustomConfig {
@Value("${custom.property}")
private String customProperty;
public String getCustomProperty() {
return customProperty;
}
}
有时候某些配置项可能不存在,或者需要一个默认值,可以在 @Value 注解中提供默认值。
@Value("${myapp.version:2.0}") // 如果没有配置 myapp.version,默认使用 2.0
private String appVersion;
五、常见的appllication.yml文件配置属性有哪些
port: 8080
servlet:
context-path: /myapp
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: myuser
password: mypassword
driver-class-name: com.mysql.cj.jdbc.Driver
level:
root: INFO
com.example: DEBUG
环境配置:可以为不同的环境(如开发、测试、生产)设置不同的配置文件。
profiles:
active: dev
自定义配置:开发者可以定义一些自定义的配置参数,在应用程序中使用。
feature:
enable-feature-x: true
max-connections: 10
通过 @Value 注解或者 @ConfigurationProperties 注解,Spring Boot 应用可以将这些配置项注入到 Java 类中。
六、开发环境、生产环境、测试环境光多种环境配置文件
在 Spring Boot 中,使用 application.yml 配置多种环境(如开发环境、测试环境、生产环境)可以通过配置不同的 profile 文件来实现。不同的 profile 文件允许为应用程序的不同运行环境配置特定的属性。
- (application.yml):定义一些全局通用的配置。
- application-{profile}.yml 文件,比如 application-dev.yml、application-prod.yml 等。每个文件对应一个环境的配置。
- application.yml 中或通过命令行/环境变量来指定当前激活的 profile。
port: 8080
spring:
application:
name: MyApp
profiles:
active: dev # 默认激活开发环境
在 application.yml 中的 spring.profiles.active 用于指定默认激活的环境配置文件,这里默认使用 dev 环境。
datasource:
url: jdbc:mysql://localhost:3306/devdb
username: devuser
password: devpassword
logging:
level:
root: DEBUG
3. application-prod.yml - 生产环境
datasource:
url: jdbc:mysql://localhost:3306/proddb
username: produser
password: prodpassword
logging:
level:
root: INFO
server:
port: 8081
4. application-test.yml - 测试环境
datasource:
url: jdbc:h2:mem:testdb # 使用 H2 内存数据库
username: sa
password: password
logging:
level:
root: WARN
profiles:
active: prod # 改为生产环境
java -jar myapp.jar --spring.profiles.active=prod
export SPRING_PROFILES_ACTIVE=prod
如果使用 Maven 构建项目,可以在 pom.xml 中配置 Maven profile 激活:
<profile>
<id>dev</id>
<properties>
<spring.profiles.active>dev</spring.profiles.active>
</properties>
</profile>
<profile>
<id>prod</id>
<properties>
<spring.profiles.active>prod</spring.profiles.active>
</properties>
</profile>
</profiles>
- (application.yml):包含所有环境通用的配置,并通过 spring.profiles.active 设置默认激活的环境。
- (application-{profile}.yml):每个环境有自己独立的配置文件,如 application-dev.yml、application-prod.yml,其中存放特定环境下的配置。
- application.yml、命令行、环境变量、Maven 配置等方式激活指定环境。
这样就可以为不同的环境(开发、测试、生产)配置不同的属性,而无需修改主配置文件。
七、在application.yml文件中引用属性信息
在 application.yml 文件中引用同一文件或其他文件中的属性值,可以使用 ${} 语法来进行引用。这与 application.properties 文件中的引用方式类似。
在 application.yml 文件中,你可以通过 ${} 来引用之前定义的属性。举个例子,假设你有以下属性:
name: MyApp
version: 1.0
description: ${app.name} is running version ${app.version}
description: "MyApp is running version 1.0"
如果你想引用外部配置文件中的属性,可以使用 @PropertySource 注解来加载属性文件,然后通过 ${} 进行引用。
name: MyApp
config: This is custom configuration
@PropertySource 注解加载这个外部文件并注入属性:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:custom.yml")
public class AppConfig {
@Value("${custom.config}")
private String customConfig;
public String getCustomConfig() {
return customConfig;
}
}
Spring Boot 允许你在 application.yml 文件中引用系统属性或环境变量,例如:
port: ${PORT:8080} # 如果没有设置 PORT 环境变量,默认使用 8080
在这个例子中,如果环境变量 PORT 被设置了,server.port 会引用该值;如果没有设置,则使用默认值 8080。
你也可以在代码中通过 @Value 注解来获取 application.yml 中的属性。例如:
name: MyApp
description: My awesome application
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AppProperties {
@Value("${app.name}")
private String appName;
@Value("${app.description}")
private String appDescription;
public void printProperties() {
System.out.println("App Name: " + appName);
System.out.println("App Description: " + appDescription);
}
}
通过这种方式,你可以在 Spring 组件中获取 application.yml 文件中的属性。
在 application.yml 文件中引用其他属性非常简单,可以通过 ${} 语法进行引用,不论是引用同一文件中的属性,还是引用环境变量和外部文件中的属性。使用 @Value 注解,还可以轻松地在 Java 代码中获取这些配置信息。
八、在application.yml文件配置和使用全局环境变量
在 YAML (.yml) 文件中使用的环境变量通常来自操作系统的环境配置,或者由运行时环境(如应用服务器、容器管理系统等)注入。应用程序在启动时可以通过多种方式读取这些环境变量。以下是环境变量的主要来源:
在 Windows 中,可以通过以下命令或系统设置定义环境变量:
java -Dmy.variable=value -jar my-app.jar
port: ${MY_SERVER_PORT:8080}
在这里,${MY_SERVER_PORT} 是环境变量,如果没有定义,它会使用默认值 8080。
可以在 docker-compose.yml 中通过 environment 配置环境变量:
myapp:
image: myapp:latest
environment:
- MY_VARIABLE=value
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mycontainer
image: myapp:latest
env:
- name: MY_VARIABLE
value: value
例如,在 GitLab CI 中的 .gitlab-ci.yml 文件中:
MY_VARIABLE: value
build:
runs-on: ubuntu-latest
env:
MY_VARIABLE: value
application.yml 可以通过 ${} 的语法引用环境变量。例如:
datasource:
url: jdbc:mysql://${DB_HOST:localhost}:3306/mydb
username: ${DB_USERNAME:root}
password: ${DB_PASSWORD:secret}
在这个例子中,DB_HOST、DB_USERNAME 和 DB_PASSWORD 是环境变量,如果这些变量没有在系统中定义,应用程序将使用提供的默认值(如 localhost、root 和 secret)。
YAML 文件中的环境变量主要从操作系统、容器平台、CI/CD 管道、启动脚本、以及外部配置管理工具获取。它们可以通过 ${} 语法在 yml 文件中被引用,并且通常可以设定默认值,以便在未定义环境变量时使用。