溫馨提示×

springboot怎么加載yml配置文件

小億
167
2023-12-14 17:06:19
欄目: 編程語言

Spring Boot 默認(rèn)會加載 application.yml 或者 application.properties 配置文件。在 Spring Boot 項(xiàng)目中,我們可以通過在 pom.xml 文件中添加 spring-boot-starter-parent 依賴來使用 Spring Boot,并且在 src/main/resources 目錄下創(chuàng)建 application.yml 文件來存放配置。

以下是一個簡單的 application.yml 配置文件示例:

server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/mydatabase username: root password: password

在上述示例中,我們指定了服務(wù)器端口為 8080,并配置了數(shù)據(jù)庫連接參數(shù)。

在 Spring Boot 應(yīng)用程序中,可以使用 @Value 注解或者 @ConfigurationProperties 注解來加載配置文件中的屬性值。以下是兩種方式的示例:

使用 @Value 注解加載配置文件屬性值:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public 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 項(xiàng)目中,就可以加載配置文件中的屬性值了。

0