首页 > 编程语言 > 详细

SpringBoot读取配置值的方式

时间:2019-07-31 02:37:06      阅读:89      评论:0      收藏:0      [点我收藏+]

SpringBoot读取配置值的方式

方法一:

@Value注解的方式取值

设定appliction.properties的配置信息

xiaoming.sex=boy
xiaoming.age=18
xiaoming.score=98

使用@Value取值

@RestController
public class PersonController {
    @Value("${xiaoming.sex}")
    private String sex;
    @Value("${xiaoming.age}")
    private Integer age;
    @Value("${xiaoming.score}")
    private Integer score;

    @RequestMapping("/xiaoming")
    public String get() {
        return String.format("小明==》性别:%s-----年龄:%s-----分数:%s",sex,age,score);
    }
}

页面展示

小明==》性别:boy-----年龄:18-----分数:98

方法二:

使用@ConfigurationProperties赋值给实体类

设定appliction.yml的配置信息

person:
  name: xiaoming
  age: 18

@ConfigurationProperties赋值给实体类

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;

    private Integer age;

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

请求信息

@Autowired
    private Person person;

    @RequestMapping("/person")
    public String getPerson() {
        return String.format("姓名:%s-----年龄:%s",person.getName(),person.getAge());
    }

页面展示

姓名:xiaoming-----年龄:18

方法三:

通过注入获取Environment对象,然后再获取定义在配置文件的属性值

设定appliction.properties的配置信息

springboot.test=hello-springboot

获取Environment对象,然后再获取定义在配置文件的属性值

 private static final String hello = "springboot.test";
    @Autowired
    private Environment environment;

    @RequestMapping("/enviro")
    public String getenv() {
        return String.format("测试Environment:" + environment.getProperty(hello));
    }

页面展示

测试Environment:hello-springboot

源码地址????????

SpringBoot读取配置值的方式

原文:https://www.cnblogs.com/ghostxbh/p/11273389.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!