springboot如何读取自定义yml配置文件

avatar
作者
猴君
阅读量:0

在Spring Boot中,可以通过@ConfigurationProperties注解来读取自定义的YAML配置文件。首先在application.propertiesapplication.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();     }  } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!