= Struts 2との統合 =
To install the Guice Struts 2 plugin with Struts 2.0.6 or later, simply include guice-struts2-plugin-1.0.jar in your web application's classpath and select Guice as your ObjectFactory implementation in your struts.xml file:
{{{
}}}
Guice will inject all of your Struts 2 objects including actions and interceptors. You can even scope your actions. You can optionally specify a Module for Guice to install in your struts.xml file:
{{{
}}}
If all of your bindings are implicit, you can get away without defining a module at all.
A Counting Example
Say for example that we want to count the number of requests in a session. Define a Counter object which will live on the session:
{{{
@SessionScoped
public class Counter {
int count = 0;
/** Increments the count and returns the new value. */
public synchronized int increment() {
return count++;
}
}
}}}
Next, we can inject our counter into an action:
{{{
public class Count {
final Counter counter;
@Inject
public Count(Counter counter) {
this.counter = counter;
}
public String execute() {
return SUCCESS;
}
public int getCount() {
return counter.increment();
}
}
}}}
Then create a mapping for our action in our struts.xml file:
{{{
/WEB-INF/Counter.jsp
}}}
And a JSP to render the result:
{{{
<%@ taglib prefix="s" uri="/struts-tags" %>
Counter Example
Hits in this session:
}}}
We actually made this example more complicated than necessary in an attempt to illustrate more concepts. In reality, we could have done away with the separate Counter object and applied @SessionScoped to our action directly.