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

   2024-10-01 8910
核心提示:在Spring Boot中,可以通过@ConfigurationProperties注解来读取自定义的YAML配置文件。首先在application.properties或applicati

在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;@RestControllerpublic class MyController {    @Autowired    private CustomProperties customProperties;    @GetMapping("/custom")    public String getCustomProperties() {        return customProperties.getProperty1() + ", " + customProperties.getProperty2();    }}

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号