Tuesday, October 07, 2014

Injecting and Binding Objects to Spring MVC Controllers

I have written two previous posts on how to inject custom, non Spring specific objects into the request handling methods of a controller in Spring MVC. One was using HandlerMethodArgumentResolver
the other with @ModelAttribute.

An adventurous reader of these posts would have discovered, that even if you remove the implemented HandlerMethodArgumentResolver or the @ModelAttribute annotation the custom objects would still be instantiated and provided to the controller method!

Yes, try it!

The only problem is that the properties of the instantiated object would be null, that is they won't have been initialized (this won't be the case though, if these properties are instantiated in the default constructor).


Monday, October 06, 2014

Using Spring's Type Converter to Inject Objects into Spring MVC Controllers

The pattern of having the identity of a resource articulated in the URL is not uncommon; In fact it is one of the ways of expressing RESTful end points...for example in an application that displays details about people, you can have a URL expressed thus:

http://www.example.com/people/777

where 777 is the number that serves as the identifier used to fetch the resources, in this case that could be the corresponding Person Object with an identifier of 777.

It wont be taking it too far then, if we see the number 777, as a direct mapping to the Person object with an id of 777.

In fact the controller method that maps the the URL above may simply have logic that get's the 777 part of the URL and use it to fetch the corresponding entry in the database backing the application. for example:


Injecting Objects into Spring MVC Controller Using @ModelAttribute Annotation

In How to Inject Objects Into Spring MVC Controller Using HandlerMethodArgumentResolver, I showed how to implement the HandlerMethodArgumentResolver interface in other to have a custom object passed as a method argument of a Spring MVC controller.

This post looks at how to still pass objects into the Spring MVC controller, but using a some what different approach: The @ModelAttribute annotation.

The @ModelAttribute annotation can be used to designates operation that can both retrieve and put stuff into the model. Its functionality depends on where it is placed...two places actually: On controller methods and on controller's method arguments.

When @ModelAttribute is placed on a controller's method, it allows the putting of stuff into the Model and when on a controller method arguments, it allows retrieving stuff from the Model...

I thus, like to think of @ModelAttribute as an annotation driven mechanism for writing and reading from the Model.

This post would look at these two methods of using @ModelAttribute and how it can be used to inject objects into controller's methods.