一、Spring Boot配置文件基础
1.1 常用配置文件格式
Spring Boot支持两种配置文件格式:properties
和 YAML
。
1.1.1 Properties格式
application.properties
文件是最常见的配置文件格式。它以键值对的形式配置内容,格式简单直观。
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
1.1.2 YAML格式
application.yml
文件使用YAML格式,它通过缩进和层次结构组织配置内容,更加清晰易读,尤其是在管理复杂的嵌套配置时。
server:port: 8080
spring:datasource:url: jdbc:mysql://localhost:3306/mydb
1.2 配置文件的加载顺序
Spring Boot允许在不同的环境中使用不同的配置文件。配置文件的加载顺序如下:
- 命令行参数:最高优先级。
application.properties
或application.yml
文件:存在于类路径下的文件。@PropertySource
注解:显式加载的外部配置文件。- 默认配置:例如
application.properties
文件中的默认配置。
此外,Spring Boot支持通过 spring.profiles.active
属性来激活不同的环境配置文件,例如 application-dev.properties
和 application-prod.properties
。
二、高级配置文件用法
2.1 多环境配置
在实际开发中,我们通常会根据不同的环境(开发、测试、生产)使用不同的配置。Spring Boot通过 profile
特性简化了多环境配置的管理。
2.1.1 定义多环境配置文件
你可以为不同的环境创建不同的配置文件,例如 application-dev.yml
和 application-prod.yml
。
# application-dev.yml
server:port: 8080
spring:datasource:url: jdbc:mysql://localhost:3306/devdb
# application-prod.yml
server:port: 80
spring:datasource:url: jdbc:mysql://localhost:3306/proddb
2.1.2 激活特定环境
可以通过以下几种方式激活某个环境的配置文件:
- 在命令行参数中指定:
--spring.profiles.active=prod
- 在
application.properties
文件中设置:spring.profiles.active=prod
- 在操作系统环境变量中设置:
SPRING_PROFILES_ACTIVE=prod
2.1.3 合并多环境配置
在多环境配置中,Spring Boot会首先加载 application.yml
或 application.properties
中的默认配置,然后加载对应的环境配置。环境配置中的内容会覆盖默认配置。
# application.yml
server:port: 8080
spring:datasource:username: root
# application-prod.yml
spring:datasource:url: jdbc:mysql://localhost:3306/proddbusername: admin # 覆盖默认配置中的username
2.2 配置属性的外部化
Spring Boot支持将配置属性外部化,以便在不同的环境中动态调整配置。外部化配置可以通过环境变量、命令行参数、以及其他外部配置文件实现。
2.2.1 环境变量
Spring Boot可以自动读取系统环境变量,并将其作为配置属性。
export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/externaldb
在应用程序中可以直接使用:
spring.datasource.url=${SPRING_DATASOURCE_URL}
2.2.2 命令行参数
可以通过命令行参数传递配置项:
java -jar myapp.jar --server.port=9090
2.2.3 外部配置文件
你可以将配置文件存储在外部目录,并通过 spring.config.location
属性指定该配置文件的路径。
java -jar myapp.jar --spring.config.location=/path/to/external-config/
2.3 配置文件中的占位符与SpEL表达式
Spring Boot的配置文件支持使用占位符(${}
)和Spring表达式语言(SpEL)进行动态配置。
2.3.1 占位符
占位符可以用于引用配置文件中的其他属性,甚至是系统环境变量。
app.name=MyApp
app.description=${app.name} 是一个Spring Boot应用程序
app:name: MyAppdescription: ${app.name} 是一个Spring Boot应用程序
2.3.2 SpEL表达式
Spring Boot还支持在配置文件中使用SpEL表达式,可以动态计算配置值。
app.port=${server.port:8080} # 使用server.port,如果未定义则默认8080
app.name=MyApp
app.fullname=#{app.name + ' Application'}
app:name: MyAppfullname: "#{app.name + ' Application'}"
2.4 自定义配置属性
除了使用Spring Boot提供的默认配置属性外,你还可以根据业务需求自定义配置属性,并通过注解将这些属性注入到Java类中。
2.4.1 定义自定义属性
首先,在配置文件中定义自定义属性:
myapp:url: https://www.example.comfeature:enabled: true
2.4.2 创建配置类
然后,在Java类中创建一个配置类,将配置文件中的自定义属性绑定到该类中:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {private String url;private Feature feature;// Getter和Setter方法public static class Feature {private boolean enabled;// Getter和Setter方法}
}
2.4.3 使用自定义属性
最后,在其他组件中注入并使用这个配置类:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class MyAppController {@Autowiredprivate MyAppProperties myAppProperties;@GetMapping("/config")public String getConfig() {return "URL: " + myAppProperties.getUrl() +", Feature Enabled: " + myAppProperties.getFeature().isEnabled();}
}
2.5 加密敏感信息
在实际应用中,有些配置信息是敏感的,例如数据库密码、API密钥等。这些信息不应该以明文形式存储在配置文件中。Spring Boot提供了几种加密敏感信息的方法。
2.5.1 使用Jasypt加密
Jasypt(Java Simplified Encryption)是一个简单的加密库,可以很方便地与Spring Boot集成。
- 添加依赖:
<dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.4</version>
</dependency>
- 配置加密属性:
使用Jasypt加密工具加密敏感信息,例如数据库密码:
# 加密命令示例
java -cp jasypt-1.9.3.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI \input="mysecretpassword" password="encryptionkey" algorithm="PBEWithMD5AndDES"
将生成的密文放入配置文件中,并使用 ENC()
包裹:
spring.datasource.password=ENC(j5dJ7d5RzQ==)
- 配置解密密钥:
通过命令行或环境变量传递解密密钥:
java -jar myapp.jar --jasypt.encryptor.password=encryptionkey
2.5.2 使用Spring Cloud Config加密
如果你的项目使用了Spring Cloud Config,那么可以利用它的加密功能。你只需要在配置服务器中启用加密,并将敏感信息加密后存储在远程配置库中。
2.6 动态刷新配置
Spring Boot的默认配置加载机制要求在启动时加载配置文件,这意味着应用运行时不能动态更新
配置。不过,Spring Cloud的 Spring Cloud Config
和 Spring Cloud Bus
提供了动态刷新配置的能力。
2.6.1 使用Spring Cloud Config
首先,确保你的项目已经集成了Spring Cloud Config,并且配置服务器已设置好。
- 添加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
- 启用动态刷新:
在需要动态刷新的配置类上添加 @RefreshScope
注解:
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RefreshScope
public class MyAppController {// 你的代码...}
- 触发刷新:
配置更改后,通过 POST
请求 /actuator/refresh
端点触发刷新。
curl -X POST http://localhost:8080/actuator/refresh
2.7 高级日志配置
日志是应用程序的关键部分,Spring Boot提供了丰富的日志配置支持。你可以在 application.properties
或 application.yml
文件中配置日志级别、输出格式等。
2.7.1 配置日志级别
Spring Boot默认使用 logback
作为日志框架,你可以通过 logging.level
属性设置日志级别。
logging.level.root=INFO
logging.level.com.example=DEBUG
2.7.2 自定义日志格式
你可以通过配置 logback-spring.xml
文件来自定义日志格式。该文件需要放置在 src/main/resources
目录下。
<configuration><appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern></encoder></appender><root level="INFO"><appender-ref ref="STDOUT" /></root>
</configuration>
2.8 处理多语言配置
在国际化应用中,需要根据用户的语言环境动态切换应用显示的语言。Spring Boot通过 MessageSource
和资源文件支持多语言配置。
2.8.1 配置资源文件
在 src/main/resources
目录下创建不同语言的资源文件,例如 messages.properties
(默认)、messages_zh_CN.properties
(中文)。
# messages.properties
greeting=Hello, {0}!# messages_zh_CN.properties
greeting=你好, {0}!
2.8.2 配置MessageSource
在Spring配置类中定义 MessageSource
Bean:
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;@Configuration
public class MessageConfig {@Beanpublic MessageSource messageSource() {ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();messageSource.setBasename("classpath:messages");messageSource.setDefaultEncoding("UTF-8");return messageSource;}
}
2.8.3 使用国际化资源
在应用中,通过 MessageSource
获取国际化信息:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.Locale;@RestController
public class GreetingController {@Autowiredprivate MessageSource messageSource;@GetMapping("/greet")public String greet(@RequestParam(name = "name", defaultValue = "World") String name, Locale locale) {return messageSource.getMessage("greeting", new Object[]{name}, locale);}
}
通过不同的 Accept-Language
头请求,可以获取对应语言的问候语。
三、总结
Spring Boot配置文件的高级用法为应用程序的灵活配置和管理提供了强大的支持。无论是多环境配置、外部化属性、加密敏感信息,还是动态刷新配置和国际化支持,这些特性都使得Spring Boot能够更好地适应各种复杂的应用场景。掌握这些高级用法,将帮助你构建更加健壮、灵活和可维护的Spring Boot应用程序。
在实际项目中,你可以根据需求灵活运用这些配置技巧,不断优化应用的配置管理方式,为你的Spring Boot项目保驾护航。