温馨提示×

springboot怎么读取yml文件属性

小亿
89
2024-08-23 02:04:46
栏目: 编程语言

Spring Boot可以通过在application.yml文件中定义属性来读取属性。可以使用@Value注解或@ConfigurationProperties注解来读取yml文件中的属性。

  1. 使用@Value注解读取属性:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {

    @Value("${myproperty}")
    private String myProperty;

    public void doSomething() {
        System.out.println("My Property: " + myProperty);
    }
}
  1. 使用@ConfigurationProperties注解读取属性: 首先在application.yml文件中定义属性:
my:
  property: value

然后创建一个配置类来读取属性值:

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

@Component
@ConfigurationProperties(prefix = "my")
public class MyProperties {

    private String property;

    public String getProperty() {
        return property;
    }

    public void setProperty(String property) {
        this.property = property;
    }
}

在其他类中可以直接注入这个配置类,并使用属性值:

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

@Component
public class MyComponent {

    @Autowired
    private MyProperties myProperties;

    public void doSomething() {
        System.out.println("My Property: " + myProperties.getProperty());
    }
}

通过以上方法,Spring Boot就可以读取并使用yml文件中的属性值。

0