溫馨提示×

java怎么獲取yml中的配置值

小億
310
2023-11-28 12:15:32
欄目: 編程語言

要獲取YAML文件中的配置值,可以使用Spring Boot提供的@ConfigurationProperties注解。以下是獲取YAML配置值的步驟:

  1. 在你的Spring Boot應用程序的配置類上添加@ConfigurationProperties注解,并指定YAML文件的前綴。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "your-prefix")
public class YourConfigClass {
    private String yourProperty;

    public String getYourProperty() {
        return yourProperty;
    }

    public void setYourProperty(String yourProperty) {
        this.yourProperty = yourProperty;
    }
}
  1. 在YAML文件中定義你的配置項,使用與Java類屬性對應的鍵。
your-prefix:
  your-property: value
  1. 在你的應用程序中使用@Autowired注解將配置類注入到你的類中,并訪問配置值。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class YourApplication {
    @Autowired
    private YourConfigClass yourConfigClass;

    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }

    public void someMethod() {
        String propertyValue = yourConfigClass.getYourProperty();
        // 使用配置值進行操作
    }
}

這樣,你就可以從YAML文件中獲取配置值并在應用程序中使用它們了。

0