Is there any way of using an immutable object as a model within a view-state in Spring webflow? I know Spring webflow generally tends towards setters for this kind of thing, but I was wondering if anyone knew of a custom DataBinder or WebDataBinder that could handle binding the data using a constructor?
I'm also aware there's this (SPR-1488) JIRA task against the problem, which advocated direct field access. Do people advocate this way of doing things? To me it doesn't quite feel right.
Thanks,
Stuart
In fact, spring beans are immutable by idea, even though you are not enforcing this. You can provide only a getter to a final field that is initialized through constructor injection. Show activity on this post. You can keep classes immutable and still use Dependency Injection if you use constructor-based injection.
It turns out you can serialize immutable objects because there's no requirement that there be a public no-argument constructor.
Data classes has a restriction to have at-least one primary constructor parameter so no default/no-args constructor is available by default in data classes. Jackson is unable to find the default constructor so it's unable to create an object of Person class and throwing the InvalidDefinitionException exception.
In Java, when we create an object of an immutable class, we cannot change its value. For example, String is an immutable class. Hence, we cannot change the content of a string once created. Besides, we can also create our own custom immutable classes.
I have put an example of how you can do this using Jackson's ObjectMapper (which besides JSON does a good job mapping anything to immutable objects ).
https://gist.github.com/4458079
A couple of things to note is that you can't use @ModelAttribute
if you want to use Spring's validation (BindingResult
) unless you replace all the argument resolvers. However @Valid
(with validation) should work and @RequestBody
will also work (with out validation) with my solution.
Although its using Jackson to map request parameters to objects there is no JSON processing involved. If you want that see MappingJacksonHttpMessageConverter.
As a feeble shameless plug I needed this in conjunction with my Immutable ORM called: JIRM as I prefer immutable objects for message driven architectures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With