When the DataBinder uses setters it uses request parameters and path variables to fill the object. 😃
Given a class Customer:
class Customer {
private int id;
private String name;
public void setId(int id) { this.id = id;}
public void setName(String name) {this.name = name;}
@Override public String toString() {return id + ":" + name;}
}
and a class CustomerController:
@RestController
@RequestMapping("customers")
class CustomerController {
@PostMapping("{id}")
void create(Customer customer) {
System.out.println(customer);
}
}
when you do a POST request to localhost:8080/customers/1?name=rod, the Customer is nicely filled and 1:rod appears on the console.
When the DataBinder uses a parametrized constructor it does not use path variables. 😟
Given a class Supplier:
class Supplier {
private final int id;
private final String name;
Supplier(int id, String name) {this.id = id; this.name = name;}
@Override public String toString() {return id + ":" + name;}
}
}
and a class SupplierController:
@RestController
@RequestMapping("suppliers")
class SupplierController {
@PostMapping("{id}")
void create(Supplier supplier) {
System.out.println(supplier);
}
}
when you do a POST request to localhost:8080/suppliers/1?name=rod, you get
java.lang.NoSuchMethodException: org.example.databinder.Supplier.<init>().
Comment From: rstoyanchev
This was covered by the changes for #26721, and in particular by ea398d7b7e72d1e1a9f7a002a291f4e0b8660e70.