宋子宪博客

SpringBoot使用@ConfigurationProperties注解映射

通过注解@ConfigurationProperties(prefix="配置文件中的key的前缀")可以将配置文件中的配置自动与实体进行映射,试例

application.properties配置如下:

person:
  name: xiaoming
  age: 10

或者,application.yml配置如下:

person:
  name: xiaoming
  age: 10

实体Bean代码如下:

@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {

    private String name;
    private Integer age;

    @RequestMapping("/test01")
    @ResponseBody
    public String test01(){
        return "springboot 访问成功! name="+name+",age="+age;
    }

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

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

pom.xml中配置@ConfigurationProperties的执行器的依赖

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

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »