springboot怎么读取yml配置文件

537
2023/12/21 12:29:58
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Spring Boot中,可以通过使用@ConfigurationProperties注解来读取yml配置文件。

首先,需要在Spring Boot应用的配置类上添加@ConfigurationProperties注解,并指定yml配置文件的前缀。例如,如果要读取application.yml文件中的配置,可以在配置类上添加@ConfigurationProperties(prefix = “配置前缀”)注解。

接下来,在配置类中定义与yml配置文件中的配置项对应的属性,并为这些属性添加相应的getter和setter方法。

最后,通过在其他类中注入配置类的实例,即可使用配置文件中的配置项。

下面是一个示例:

在application.yml中定义了一个名为example的配置项:

example:
  name: "John"
  age: 25

创建一个配置类ExampleConfig来读取yml文件中的配置项:

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "example")
public class ExampleConfig {
    private String name;
    private int age;

    // getter和setter方法省略

    // 其他类中使用ExampleConfig的实例
}

现在,可以在其他类中注入ExampleConfig的实例,并使用其中的属性:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ExampleService {
    private ExampleConfig exampleConfig;

    @Autowired
    public ExampleService(ExampleConfig exampleConfig) {
        this.exampleConfig = exampleConfig;
    }

    public void printExample() {
        System.out.println("Name: " + exampleConfig.getName());
        System.out.println("Age: " + exampleConfig.getAge());
    }
}

在上面的示例中,ExampleService类通过构造函数注入ExampleConfig的实例,并使用其属性来打印配置项的值。

注意:在使用@ConfigurationProperties注解时,需要确保所使用的yml配置文件已经正确加载到Spring Boot应用中。可以通过在application.properties文件中添加spring.profiles.active=dev来指定使用的配置文件。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: SpringBoot中怎么集成Swagger文档