spring-bootpropertiesyamlmodelattribute

SpringBoot: ModelAttribute default property through yml file not working


Age limit default value is not picked by ModelAttribute, However it was working fine with request parameter.

YML File

age:            
    default:
        limit:  60  

Below is old Code with Request Parameter Request

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

Below is new Code with ModelAttribute Request

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
}

Solution

  • 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) {}
    

    }