Immutable objects and Spring/Spring MVC: the right choice?

2 Answers

I sometimes create separate immutable "design model" classes and mutable (Java Bean) "MVC model" classes to avoid those kinds of problem.

I usually try to design my classes as immutable classes, so I have a lot of advantages in terms of coding stress.

But working with Spring, I sometimes notice that the framework "discourages" this kind of design in most cases, in favour of classic JavaBeans design: default constructor + getters/setters.

I really don't like JavaBean designed objects because of their insane mutability. So I'm wondering if I'm missing something...

I try to keep my classes design as elegant and reusable as possible, but a framework requires to change this design or allow it in a difficult way...

What's wrong with this?

Spring Webflow DataBinding to immutable objects via a constructor?

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 ).

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.