Spring Boot 使用@ConfigurationProperties注解获取配置文件中的值

来源:互联网 发布:淘宝冲q币怎么买 编辑:程序博客网 时间:2024/05/29 03:03

如果在开发的时候,我们往往会动态的配置一些属性,而且这些属性在代码中大量使用,我们可以将这个属性配置到application-development.yml(也可以是其他),然后通过@ConfigurationProperties注解来进行动态配置。

在application-development.yml中配置添加一个属性

test:  property:    name: Jeason    password: 123456

然后我们可以对这个配置进行统一的配置,写一个配置类TestPropertyConfig

@Configurationpublic class PropertyTestConfig {    @Bean    @ConfigurationProperties(prefix = "test")    public TestProperties testProperties(){        return new TestProperties();    }    public static class TestProperties{        Map<String, String> property = new HashMap<String, String>();        //获取test下面的property 的值然后放在Map中        public Map<String, String> getProperty() {             return this.property;        }    }}

好了,这里我们就将配置中的test这个属性放入了PropertyTestConfig这个配置类中。直接使用@AutoWired 注入
PropertyTestConfig.TestProperties

@Controllerpublic class TestController {    @Autowired    private PropertyTest.TestProperties testProperties;    @RequestMapping({"/","/index"})    @ResponseBody    public String index(){      String name=testProperties.      getProperty().get("name");        return name;    }    @RequestMapping("test")    public String test(){        return "error";    }}

最后将会返回Jeason这个值

阅读全文
1 0
原创粉丝点击