Warning about primitive ModelAttribute

Recently while working with Spring Framework 3.0, I stumbled upon a trap that might be a bug of Spring Framework. It costs our team lots of time & efforts, since the bug is like a mystery that happens randomly. Eventually we decide to take a work around, but it’s still take lots of time to change the way the system was working.

The mystery is called Model Attribute, a handy utility supported by Spring 3.x.

Personally, I like this feature a lot. The ModelAttribute Annotation way gives me the ability to declare and init a variable just once, then it will be automatically added into model of any action. For example:

public User getCurrentUser() {
return userService.getCurrentUser();

But a problem happen here & there when I use primitive type (long, int, …) or even their wrapper type (Long, Integer,…) for the ModelAttribute. An error just pop out of nowhere:

java.lang.NoSuchMethodException: long.()<init>

Following my senior hint, I even comes to the code of Spring Framework, and actually see that it try to call the default constructer of Long type. Since that constructer does not exist (certainly), it fails and brings up the error. The headache is that this thing does not always happen: I still can not figure what trigger it up. But the fact that it’s out there make me & our team change the course of the program: instead of an tidy assignment, now we need to call the same function again & again whenever we need that modelAttribute (almost always in my case).

I have put a question out there in StackOverflow, but it still get no-good answer. I wonder if I should raise a bug for Spring… but until then I think that this “brilliant” way shouldn’t be used.

Hope this post is useful for anyone come across the same problem.

2 thoughts on “Warning about primitive ModelAttribute

Comments are closed.