Friday, 16 January 2009

More Spring - Using Session Scope

We're in the process of a major refactor which will see lots of stuff being moved from our wicket application object and session objects into our spring configuration. The motivation for this was that the session and application objects are obtained as static instances, eg Session.get(). This approach is not particularly testable, though we did find a way to initialise the session and application using Session.set(). The problem was that because we were using our application object as a service locator as suggested here our application object was very heavy causing lots of beans to be loaded during tests. I didn't really like having to supply beans with Session and Application objects as I felt it was tying us unnecessarily to the workings of the web app.

I decided it would be a lot cleaner if we were to have session scoped beans for session data. Doing so requires a RequestContextListener in your web.xml:


<web-app>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
  </listener>
  ...
</web-app>


So now I can move things out of the session and into spring meaning my session is not cluttered and my tests do not depend on an instance of my session object.

In addition we've also moved to using the @SpringBean annotation from wicket-spring. This enables us to annotate dependencies within wicket components with @SpringBean. This results in serializable proxies being created. This means we can move away from the service locator approach where everything is inside the application object. This approach gets round the problem that anything injected into a component by regular spring methods would be serialized. Instead of calling ((MyApplication)Application.get()).getUserService() wherever we needed a service we can now just use userService and know that it will have been injected for us.

The spring-wicket wiki entry is really helpful if you're trying to use the two technologies together.

No comments: