温馨提示×

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

小亿
363
2024-08-11 17:28:36
栏目: 编程语言

在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();
    }

}

0