Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Injected Class

Tags:

java

spring

I am new to working with Spring and I just joined a team of developers that is utilizing it for the product we are working on. I am beginning to understand IoC. However, I am flummuxed on one particular point. I have searched for an answer, but have been unable to find anything.

The class I am looking at has the @Controller annotation set on it. One of the methods has the @RequestMapping annotation. The method signature of this particular method contains a parameter for one of my company's proprietary classes. This proprietary class does not have any annotations on it for Spring nor is it listed in the Spring configuration file.

So, my question is: how does that parameter get injected when there isn't anything to help the framework identify it?

I suspect that it is able to do this because on the previous transaction the proprietary class is added to the Model via ModelAndView.addObject(), but I was hoping someone could confirm or deny.

The particular scenario is this:

  1. user requests login page
  2. addObject(proprietaryClass)
  3. user presented with login page
  4. user clicks button to login
  5. method is called with proprietary class in method signature.

Any help would be great.

like image 257
Shadraq Avatar asked Dec 05 '25 23:12

Shadraq


2 Answers

Spring is smart... real smart. It can look at the names of the request parameters and map them to POJOs by field name. For instance, if your user has a "first" and "last" fields, you could pass in user.first=Joe&user.last=Blow and it would attempt to set the "first" and "last" properties of your user object. Have a look at http://www.jpalace.org/docs/technotes/spring/mvc-params.html specifically the section named Binding Domain Objects.

Another option is that they have implemented a converter, or converter factory. In my project I implemented a generic ConverterFactory that handles any of my database entities, takes a Long and converts it to the materialized entity by looking it up by id.

like image 139
digitaljoel Avatar answered Dec 07 '25 13:12

digitaljoel


Somewhere in your beans configuration you'll find a conversion service bean. If the other developers are nice, they will name it something like "ConverterFactory", and it will probably extend org.springframework.format.support.FormattingConversionServiceFactoryBean. You can also grep the codebase for org.springframework.format.FormatterRegistry.

This is described in the Spring Reference Manual.

like image 30
parsifal Avatar answered Dec 07 '25 12:12

parsifal