Leverage the Spring Support
Another notable feature of Wicket 1.4 is that it has built-in
Spring support. This allows you to configure objects and services using Spring once, then use the Wicket Spring integration to inject these objects and services magically into your Wicket components. You will typically find yourself using Spring injection for data-access objects, but that is not the only use.
To start using Spring integration, add the wicket-spring dependency to your pom.xml, as follows:
<dependency>
<groupId>org.apache.wicket</groupId>
<artifactId>wicket-spring</artifactId>
<version>1.4-SNAPSHOT</version>
</dependency>
Also, modify your web.xml to load up the Spring application context XML file when your Wicket web application starts up. Add the following lines to your web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Now, create the applicationContext.xml file in your WEB-INF directory. The applicationContext.xml file contains all the Spring beans that you want to create once for your web application.
Implement Dependency Injection
In order for Spring to inject dependencies into your web application, modify your web application's init() method by adding the following line:
addComponentInstantiationListener(new SpringComponentInjector(this));
This will force the Page (or anything derived from a Wicket component) to have its dependencies injected when created.
Now, you can introduce a member variable marked with a @SpringBean annotation in any page or component class, and this member variable will be initialized from the application context each time the page or component class is instantiated. Unlike injections at the doctor's office, this one is painless.
Occasionally, I need to use the application context outside of a Wicket component, for example in a Wicket session. Digging deep into the Wicket code, I found out how to use Spring beans in my Wicket session. In my web application class, I have the following method:
public ApplicationContext getApplicationContext()
{
return WebApplicationContextUtils
.getRequiredWebApplicationContext(getServletContext());
}
Now, I can use this method from my session, or from almost anywhere else, like so:
ApplicationContext applicationContext = ((WicketLearningApplication) Application.get()).getApplicationContext();
Congratulations! You have ventured on to the bleeding edge by using the nightly snapshot. Your web application will be in a great position to use Wicket 1.4 when it is releasedand with a lot less code.