I would like to know if I can populate a bean via constructor injection when receiving POST data (no matter from a system or web form). I'm wondering if this would be a better idea than having a huge number of setters, and if this might have some bad side effects I am not aware of.
I currently use a form-backing bean in Spring and implemented lots of getters/setters but mainly this bean works as a data strcuture, only holding and validating what was injected to provide the data for a template engine. If I could inject all POST data through the constructor, I could omit all setters, but at the same time the constructor would work with lots of parameters.
Is that a sensible idea, or is setter-injection best practice here ^^"
The answer to my question is basically this [post]. Even though the blog post mainly addresses the handling of immutable objects, the concept is transferable.
The author makes use of a custom WebArgumentResolver. Basically, you pick the arriving post data by hand and call your bean's constructor to populate it's fields.
Additionally, in the comment section there's mentioned that you could use the Spring DataBinder class, as well. The hint about the
binder.initDirectFieldAccess();
was a good-to-know remark.This way it's easy to slim my bean, so it no longer has to pretend to be an object, although it's a data structure.
Taking into consideration that this seems to be a totally viable way to utilize immutable objects, I concluded that it might also serve my purpose. Although I probably won't make my bean immutable, it isn't profitable to polute the code with tons of setters and getters even though field population is possible via constructors.