Spring Boot 默认会加载 application.yml 或者 application.properties 配置文件。在 Spring Boot 项目中,我们可以通过在 pom.xml 文件中添加 spring-boot-starter-parent 依赖来使用 Spring Boot,并且在 src/main/resources 目录下创建 application.yml 文件来存放配置。
以下是一个简单的 application.yml 配置文件示例:
server:port: 8080spring:datasource:url: jdbc:mysql://localhost:3306/mydatabaseusername: rootpassword: password
在上述示例中,我们指定了服务器端口为 8080,并配置了数据库连接参数。
在 Spring Boot 应用程序中,可以使用 @Value 注解或者 @ConfigurationProperties 注解来加载配置文件中的属性值。以下是两种方式的示例:
使用 @Value 注解加载配置文件属性值:
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;@Componentpublic class MyComponent { @Value("${server.port}") private int serverPort; // getter and setter methods}使用 @ConfigurationProperties 注解加载配置文件属性值:
import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;@Component@ConfigurationProperties(prefix = "spring.datasource")public class DatabaseConfig { private String url; private String username; private String password; // getter and setter methods}将上述示例中的代码添加到 Spring Boot 项目中,就可以加载配置文件中的属性值了。

