温馨提示×

springboot怎么获取配置文件的值

小亿
86
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