首页 > 解决方案 > SpringBoot:通过yml文件的ModelAttribute默认属性不起作用

问题描述

年龄限制默认值不是由 选择的ModelAttribute,但是它与请求参数一起工作正常。

YML 文件

age:            
    default:
        limit:  60  

下面是带有请求参数请求的旧代码

public ResponseEntity<Account> getPersonAccount(@RequestParam String name,@Min(value=0) @RequestParam(required = false, defaultValue = "${age.default.limit}") Integer limit
){
}

下面是带有 ModelAttribute 请求的新代码

public ResponseEntity<Account> getPersonAccount(@ModelAttribute("person" ) Person person) {}

@Configuration
public class Person implements Serializable {
    private String name;
    @Value("${age.default.limit}" )
    private Integer limit;
    getter/setter
}

标签: spring-bootpropertiesyamlmodelattribute

解决方案


public class PersonController { 
@Value("${age.default.limit}" )
private Integer limit;

@ModelAttribute("person")
public Person populatePerson() {
    Person person = new Person();
    person.setLimit(limit);
    return user;
}

public ResponseEntity<Account> getPersonAccount(@ModelAttribute("person" ) Person person) {}

}


推荐阅读