溫馨提示×

springboot怎么獲取配置文件的值

小億
112
2024-01-11 02:41:13
欄目: 編程語言

在Spring Boot中,可以使用@ConfigurationProperties注解來獲取配置文件的值。

  1. 在application.properties或application.yml文件中定義配置項,例如:

application.properties

myapp.name=My Application
myapp.version=1.0

application.yml

myapp:
  name: My Application
  version: 1.0
  1. 創建一個配置類,并使用@ConfigurationProperties注解來綁定配置項,例如:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
    private String name;
    private String version;

    // 省略getter和setter方法

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}
  1. 在需要使用配置值的地方,通過依賴注入的方式獲取配置類的實例,例如:
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 {
    private final MyAppProperties appProperties;

    @Autowired
    public MyController(MyAppProperties appProperties) {
        this.appProperties = appProperties;
    }

    @GetMapping("/app-info")
    public String getAppInfo() {
        return appProperties.getName() + " " + appProperties.getVersion();
    }
}

在上述例子中,MyAppProperties類使用@ConfigurationProperties注解的prefix屬性指定了配置項的前綴,Spring Boot會自動將配置文件中以該前綴開頭的配置項的值綁定到該類的相應屬性上。然后,在MyController類中通過構造函數注入MyAppProperties實例,并使用該實例獲取配置值。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女