在 Spring Boot 里,环境配置管理可借助多种方式达成,以下为你详细介绍常见的方法。
1. 使用 application.properties
或 application.yml
这是最基础且常用的配置方式。
application.properties
在 src/main/resources
目录下创建 application.properties
文件,然后在其中添加配置项,示例如下:
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
application.yml
同样在 src/main/resources
目录下创建 application.yml
文件,其内容示例如下:
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
2. 多环境配置
你可以针对不同的环境(如开发、测试、生产)创建不同的配置文件。
创建不同环境的配置文件
- 开发环境:
application-dev.properties
或application-dev.yml
- 测试环境:
application-test.properties
或application-test.yml
- 生产环境:
application-prod.properties
或application-prod.yml
例如,application-dev.properties
可如下配置:
server.port=8082
spring.datasource.url=jdbc:mysql://localhost:3306/devdb
spring.datasource.username=devuser
spring.datasource.password=devpassword
指定当前使用的环境
可以通过以下几种方式指定当前使用的环境:
命令行参数
在启动应用时,使用 --spring.profiles.active
参数指定,示例如下:
java -jar your-application.jar --spring.profiles.active=dev
系统属性
在 Java 代码中设置系统属性,示例如下:
System.setProperty("spring.profiles.active", "dev");
SpringApplication.run(YourApplication.class, args);
application.properties
或 application.yml
在主配置文件中指定,示例如下:
spring.profiles.active=dev
3. 使用 @ConfigurationProperties
注解
此注解可将配置文件中的属性绑定到 Java 对象上,示例如下:
创建配置类
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppConfig {
private String apiKey;
private String secret;
// Getters and Setters
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
在配置文件中添加属性
myapp.apiKey=123456
myapp.secret=abcdef
使用配置类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@Autowired
private MyAppConfig myAppConfig;
@GetMapping("/config")
public String getConfig() {
return "API Key: " + myAppConfig.getApiKey() + ", Secret: " + myAppConfig.getSecret();
}
}
4. 使用 @Value
注解
该注解可直接注入配置文件中的属性值,示例如下:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AnotherController {
@Value("${server.port}")
private int serverPort;
@GetMapping("/port")
public String getPort() {
return "Server Port: " + serverPort;
}
}
通过上述方法,你能够在 Spring Boot 中灵活管理环境配置。