Integrating with Spring
This article demonstrates integrating MINA application with Spring. I wrote this article on my blog, and though to put it here, where this information actually belongs to. Can find the original copy at Integrating Apache MINA with Spring.
We shall take a standard MINA application which has following construct
- One Handler
- Two Filter - Logging Filter and a ProtocolCodec Filter
- NioDatagram Socket
Lets see the code first. For simplicity we have omitted the glue code.
To integrate with Spring, we need to do following:
- Set the IO handler
- Create the Filters and add to the chain
- Create the Socket and set Socket Parameters
NOTE: The latest MINA releases doesn't have the package specific to Spring, like its earlier versions. The package is now named Integration Beans, to make the implementation work for all DI frameworks.
Lets see the Spring xml file. Please see that I have removed generic part from xml and have put only the specific things needed to pull up the implementation.
This example has been derived from Chat example shipped with MINA release. Please refer the xml shipped with chat example.
Now lets pull things together
Lets set the IO Handler in the spring context file
Lets create the Filter chain
Here, we create instance of our IoFilter. See that for the ProtocolCodec factory, we have used Constructor injection. Logging Filter creation is straight forward. Once we have defined the beans for the filters to be used, we now create the Filter Chain to be used for the implementation. We define a bean with id "FilterChainBuidler" and add the defined filters to it. We are almost ready, and we just need to create the Socket and call bind
Lets complete the last part of creating the Socket and completing the chain
Now we create our ioAcceptor, set IO handler and Filter Chain. Now we have to write a function to read this file using Spring and start our application. Here's the code
We just call this method from main, and this shall initialize our MINA application.