溫馨提示×

springboot怎么讀取yml文件屬性

小億
173
2024-08-23 02:04:46
欄目: 編程語言

Spring Boot可以通過在application.yml文件中定義屬性來讀取屬性??梢允褂?code>@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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女