从入门到入门-Spring Boot-属性配置2

来源:互联网 发布:怎么用vs2015写c语言 编辑:程序博客网 时间:2024/06/02 02:55

在yml文件中添加name 、age


在Java中获取


浏览器访问http://localhost:8082/user/hello


正常获取到属性中的值!!!!!!!!


再往下看

添加李四


添加User类

package com.demo;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** * Created by chenjianfei on 2017-7-11. */@Component@ConfigurationProperties(prefix = "user")public class User {    private String userName ;    private Integer age;    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public Integer getAge() {        return age;    }    public void setAge(Integer age) {        this.age = age;    }}

Controller引入User

package com.demo;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/** * Created by chenjianfei on 2017-7-11. */@RestControllerpublic class UserController {    @Value("${name}")    private String name;    @Value("${age}")    private Integer age;    @Autowired    private User user;    @RequestMapping(value="/hello",method = RequestMethod.GET)    public String say(){        return user.getUserName()+" " +user.getAge();    }}


如果发生如下错误,请修改pom.xml



<dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-configuration-processor</artifactId>   <optional>true</optional></dependency>


最后很重要一步:

配置完还需要在spring Boot入口类加上@EnableConfigurationProperties并指明要加载哪个bean,如果不写ConfigBean.class,在bean类那边添加


重启Spring Boot,浏览器访问http://localhost:8082/user/hello




推荐一篇很好的文章 http://tengj.top/2017/02/28/springboot2/


原创粉丝点击