Tuesday, January 8, 2008

ITMill Toolkit 5 & Spring

Once again, in the perfect world of the Java frameworks, everything is simple, everything is easy.

Ok, I'll admit, I've been helped on this one, by a post from Joonas Lehtinen .

He say everything: toolkit application can be treated as servlet.
So.

Set up Spring as usual:
Add the Spring dependencies to your pom.xml :

<dependencies>
...
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>2.0.3</version>
</dependency>
</dependencies>

Add the Spring listener to your web.xml :

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

And add the relevant informations about your application context files :

<web-app>
..
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
</web-app>

Following Joonas advice, I've made a very simple helper class allowing me to access Spring beans:

import com.itmill.toolkit.Application;
import com.itmill.toolkit.terminal.gwt.server.WebApplicationContext;
import javax.servlet.ServletContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SpringContextHelper {

private ApplicationContext context;

public SpringContextHelper(Application application) {
ServletContext servletContext =
((WebApplicationContext) application.getContext())
.getHttpSession().getServletContext();
context = WebApplicationContextUtils.
getRequiredWebApplicationContext(servletContext);
}

public Object getBean(final String beanRef) {
return context.getBean(beanRef);
}
}


And... That's it. Simple, eh ?

Usage example:

public class SpringHelloWorld extends com.itmill.toolkit.Application {

public void init() {
final Window main = new Window("Hello window");
setMainWindow(main);

SpringContextHelper helper = new SpringContextHelper(this);
MyBeanInterface bean = (MyBeanInterface)
helper.getBean("myBean");
main.addComponent(new Label( bean.myMethod() ));
}
}

1 comment:

Unknown said...

Check the updated article on Vaadin forums for the integration of Spring with Vaadin 7
https://vaadin.com/wiki/-/wiki/Main/Spring+Integration