Once you use Spring’s dependency injection you will probably never want to go back to building applications without it, and at the time of this writing the DWR documentation for doing this was not smooth at all. I spent a few hours trying to figure it out and it turns out to be a very straight forward thing to do.
The DWR-Spring integration is very easy.
First, On the dwr.xml file, add your ajax class using the “spring” creator, and add to it a param with name “beanName” (this is not an arbitrary name. You have to name it exactly like that, since that’s how DWR recognices which class will be initialized trough dependency injection). The param value, which in this case is “exampleAjax” is the name of the bean specified in spring’s configuration file (which we will see in a few moments)
<param name=”beanName” value=”exampleAjax”/>
That’s it for DWR configuration. Now let’s get to spring.
First of all, I want to make a parenthesis to say that, as a good practice, I advice you to create an independent spring configuration file for the DWR classes to avoid having a long and hard to mantain xml. So, back to the point of this post, in the spring beans configuration xml, add a bean as follows:
The explanation of this snippet:
- bean name: must match DWR’S param value
- class: The class path to the class containing your ajax helper methods (the ones that you will call using DWR)
- property name: A variable that resides inside the class. In this case, my class (ExampleAjax) has a variable of type ExampleService, which contains business logic, so I want Spring to initialize it trough dependency injection
- ref bean: the spring’s bean name that will be asigned to the “property name” variable.