Use annotation @Value mapping and use annotation @ConfigurationProperties mapping

Use annotation @Value mapping

The application.yml configuration is as follows

person:
  name: zhangsan
  age: 18

The entity Bean code is as follows

@Controller
public class QuickStartController {

    @Value("${person.name}")
    private String name;
    @Value("${person.age}")
    private Integer age;


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

}

Use annotation @ConfigurationProperties mapping

The application.yml configuration is as follows:

person:
  name: zhangsan
  age: 18

The entity Bean code is as follows:

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

    private String name;
    private Integer age;

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

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

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

Note: The @ConfigurationProperties method can be used to automatically map the configuration file and the entity field, but the field must provide the set method, and the field decorated with the @Value annotation does not need to provide the set method

Guess you like

Origin blog.csdn.net/he1234555/article/details/114292522