springboot怎么获取配置文件的值

   2025-02-05 2120
核心提示:在Spring Boot中,可以使用@ConfigurationProperties注解来获取配置文件的值。在application.properties或application.yml文件中

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

在application.properties或application.yml文件中定义配置项,例如:

application.properties

myapp.name=My Applicationmyapp.version=1.0

application.yml

myapp:  name: My Application  version: 1.0
创建一个配置类,并使用@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;    }}
在需要使用配置值的地方,通过依赖注入的方式获取配置类的实例,例如:
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic 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实例,并使用该实例获取配置值。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言