在Spring Boot中,可以通過@ConfigurationProperties
注解來讀取自定義的YAML配置文件。首先在application.properties
或application.yml
文件中配置自定義的YAML文件的路徑,例如:
custom:
property1: value1
property2: value2
然后創建一個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
類作為參數傳入,例如:
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();
}
}