Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Webflow DataBinding to immutable objects via a constructor?

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

like image 984
Spedge Avatar asked Aug 15 '11 14:08

Spedge


People also ask

How can we make bean immutable in spring?

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.

Can immutable class be serializable?

It turns out you can serialize immutable objects because there's no requirement that there be a public no-argument constructor.

Why does Jackson require default 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.

Can we create custom immutable class in Java?

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.


1 Answers

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.

like image 96
Adam Gent Avatar answered Sep 20 '22 01:09

Adam Gent