Using the Guice Struts 2 plugin
03/29/2011
Guice 3.0 was released a few days ago! One of the easiest ways to use it in your web server is to use Struts 2 with the Struts 2 plugin, which is available in the central Maven repository.
This tutorial assumes familiarity with Guice and Struts 2.
In order to use it the plugin, your injector must be created with a Struts2GuicePluginModule:
Injector injector = Guice.createInjector(
new com.google.inject.servlet.ServletModule(),
new com.google.inject.struts2.Struts2GuicePluginModule(),
new MyModule());
You must then define a GuiceServletContextListener to provide the injector to the Struts 2 plugin. I injected the Injector because I’m using embedded Jetty. However, if you’re using a standard servlet container, you’d probably just create the injector in the class itself.
package com.benmccann.example;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
/**
* @author benmccann.com
*/
public class GuiceListener extends GuiceServletContextListener {
private final Injector injector;
@Inject
public GuiceListener(Injector injector) {
this.injector = injector;
}
@Override
public Injector getInjector() {
return injector;
}
}
You must then wire it up in your web.xml:
<listener>
<listener-class>com.benmccann.example.GuiceListener</listener-class>
</listener>
<filter>
<filter-name>guice</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>guice</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
There’s also an example in the Guice source code repository.
Enjoy!
Awesome example, thanks so much. I’m just having one little problem. When I try to hit an action I get this,
Unable to load configuration. – bean – jar:file:/C:/mywksp/target/my-war/WEB-INF/lib/guice-struts2-plugin-3.0.jar!/struts-plugin.xml:11:59 at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69)…..
…………
Caused by: Bean type class com.opensymphony.xwork2.ObjectFactory with the name guice has already been loaded by bean – ………/struts-plugin.xml:11:59
What could cause this?
I am also facing the same issue. Is ur issue already solved.