溫馨提示×

springboot如何讀取自定義yml配置文件

小億
347
2024-08-11 17:28:36
欄目: 編程語言

在Spring Boot中,可以通過@ConfigurationProperties注解來讀取自定義的YAML配置文件。首先在application.propertiesapplication.yml文件中配置自定義的YAML文件的路徑,例如:

custom:
  property1: value1
  property2: value2

然后創(chuàng)建一個Java類來映射這些配置,例如:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "custom")
public class CustomProperties {
    private String property1;
    private String property2;

    // getters and setters
}

在Spring Boot的啟動類中引入@EnableConfigurationProperties注解并將 CustomProperties類作為參數(shù)傳入,例如:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(CustomProperties.class)
public class MyApp {

    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }

}

這樣就可以在其他組件中注入CustomProperties類,并訪問其中的配置屬性,例如:

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 CustomProperties customProperties;

    @GetMapping("/custom")
    public String getCustomProperties() {
        return customProperties.getProperty1() + ", " + customProperties.getProperty2();
    }

}

0