Spring Boot的外部化配置允许开发者在不修改代码的情况下,通过外部的配置文件来配置应用程序的属性。
一、外部化配置的特点
- 可以使用
application.properties、application.yml等外部配置文件来配置应用程序的属性。 - 外部配置文件可以包含各种属性,如数据库连接信息、端口号、日志级别等。
- Spring Boot会自动加载并解析这些外部配置文件,将配置属性注入到应用程序中。
代码如下:
- 创建 application.properties 文件并添加以下内容:
app.message=Hello, this is a custom message
- 在应用程序中注入并使用这个配置属性:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MessageController {
@Value("${app.message}")
private String message;
@GetMapping("/message")
public String getMessage() {
return message;
}
}
在这个示例中,使用 @Value 注解将 app.message 属性值注入到 message 变量中,然后在 /message 端点中返回这个属性值。当应用程序启动时,Spring Boot会自动加载并解析 application.properties 文件,将其中定义的属性值注入到应用程序中。
原文链接: https://blog.csdn.net/2401_82884096/article/details/138294866