Friday, May 22, 2009

Unexpected behaviour when defining @SessionAttributes by type in Spring MVC

When defining model attributes that should serve as "command" objects (i.e. they span multiple requests), you have two options.

You can define them either using Type or Name e.g.


@SessionAttributes(types = {MyModelObject.class})
@SessionAttributes(names = {"myModelObject"})


I chose types originally, as at least this is something my compiler knows about - whereas a model name is just a string and will not be checked by the compiler.

However using types caused a problem I didn't expect. If you decide to pass a Hibernate-managed domain object as your model, then it may not be the type you expect it to be! It has probably been wrapped using CGLIB for lazy loading reasons behind the scenes.

So Spring cannot recognise the type of your model object, and hence it will not get set as a session scoped object. The next time you go to use it, it just won't be there, and there will be no warning or error as to why.

Tricky! So from now on I just use the NAME option instead of TYPE when defining SpringMVC @SessionAttributes.

0 comments: