Using Dependency Injection in Struts2 for stateless EJBs part 1

In this post I will present a way to use dependency injection of stateless session beans in Struts 2 actions using Guice. I will only write about EJB3, because they have simpler client lookup code, but you might be able to change the presented code to cover older versions of EJB.

We will use off the shelf Struts 2 and off the shelf Guice (with the Guice Struts 2 plug-in). No extra “glue” code is required to inject stateless EJBs into a Struts actions with Guice. In the next post I will tweak the presented code and make the binding of EJBs in Guice modules simpler.

This post is divided in two sections. In the first section we will create a simple, complete, hello-world type application using Struts 2. The application will consist of only one action that when called will print the current date in a JSP page. Then we will write a stateless session EJB and use Guice to inject the EJB into the action. If you are already familiar with Struts 2 you might want to skip the first section and go directly to the second.

A basic Struts 2.x application

Below you will find a series of steps with all code for our mini application.

1. Project setup

With your favorite IDE create an enterprise project. You need to create an enterprise project (ear based deployment) and not a web project (war based deployment) because we will create an EJB in the next section.

Now add a web module into your enterprise project and add the following jars to WEB-INF/lib: commons-logging-1.1.jar, freemarker-2.3.8.jar, ognl-2.6.11.jar, struts2-core-2.0.8.jar and xwork-2.0.3.jar.

Although I am a happy Eclipse user I have to admit that Eclipse has very basic support for Java EE 5, so for the code of this post I used Netbeans 6.0 M9 with Glassfish 2 Beta as the application server. Netbeans IMHO is not so good for Java editing but has decent support for the latest Java EE standards. Please keep in mind that the code is only tested with Glassfish 2 Beta.

2. Edit web.xml

The below code is the minimum web.xml needed for a Struts 2 application. It contains the Struts 2 filter definition (FilterDispatcher) and a welcome file (index.html) that it is used to redirect the user to the default Struts 2 action.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""

3. Create struts.xml

Now we need to create the struts.xml file. This file is located at the root of your classpath. The below code has some basic configuration parameters and includes the dates Struts package that will contain our action.

<?xml version="1.0" encoding="UTF-8" ?>
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  <constant name="struts.enable.DynamicMethodInvocation" value="false" />
  <constant name="struts.devMode" value="false" />
  <!-- Include the package with our actions -->
  <include file="dates.xml"/>

4. Create the dates Struts package

Create the dates.xml file at the root of your classpath as we specified in the above struts.xml. In this file we define a package named dates and mapped under <context-root>/dates/* URL.

<?xml version="1.0" encoding="UTF-8" ?>
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
  <package name="dates" namespace="/dates" extends="struts-default">
    <action name="CurrentDate" class="com.tzavellas.dates.web.CurrentDateAction">
    <!-- Add more actions here -->

The package contains our only action, named CurrentDate and mapped to the URL <context-root>/dates/CurrentDate.action.

5. Create the welcome file

Now we will create our welcome file that redirects the user to the Struts action. This is a simple HTML page named index.html (as defined in web.xml) and located under the context root. The page uses a meta tag to redirect to the URL of the action .

    <meta http-equiv="Refresh" content="0;URL=dates/CurrentDate.action">
    <p>Loading ...</p>

6. Code the action

Finally it’s time for some Java code. The below code is a simple Struts 2 action that when called will set the value of the currentDate property to the current date.

package com.tzavellas.dates.web;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;

public class CurrentDateAction extends ActionSupport {

  private Date currentDate;

  public String execute() throws Exception {
    currentDate = new Date();
    return SUCCESS;

  public Date getCurrentDate() {
    return currentDate;

Note that unlike Servlets or Struts 1 actions, in Struts 2 for every HTTP request a new action instance is created so it is safe to mutate an action property (like the currentDate above) with request specific data.

7. Create the view

As we defined in the dates package (dates.xml) the view for the CurrentDateAction is a JSP file localed in WEB-INF/jsp/date.jsp. The below code, for the date.jsp page, uses the Struts 2 tag library to display the value of the currentDate property of the action.

<%@ page contentType="text/html" pageEncoding="UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>The current date</title>
    <h1>The current date is: <s:property value="currentDate"/></h1>

We’ve just created a simple application with Struts 2. In the next section we are going to define a stateless session EJB3 and wire it with the above action using Guice.

For more information about the Struts 2 web framework visit the Struts 2 wiki pages.

The EJB and the integration with Guice

8. Create the stateless session EJB3

With your favorite IDE add an EJB module to the enterprise project we created in step 1.

Below we define the SLSB with a remote interface and one method that returns the current date. The bean is mapped to the global JNDI name com.tzavellas.dates.ejb.DatesManagerBean.

package com.tzavellas.dates.ejb;
import java.util.Date;
import javax.ejb.Stateless;

public class DatesManagerBean implements DatesManagerRemote {

  public Date currentDate() {
    return new Date();
package com.tzavellas.dates.ejb;
import java.util.Date;
import javax.ejb.Remote;

public interface DatesManagerRemote {
  Date currentDate();

9. Add the Guice jars in the classpath

Add guice-1.0.jar and guice-struts2-plugin-1.0.1.jar in WEB-INF/lib directory of your web module. The jar file guice-1.0.jar contains the core Guice implementation and the guice-struts2-plugin-1.0.1.jar file contains the Guice’s Struts 2 integration code.

10. Edit struts.xml to include the Guice plug-in

Struts 2 is a very flexible framework. One of Struts’ many extensions is the ObjectFactory plug-in interface. The responsibility of an ObjectFactory is to create the objects managed by Struts. An ObjectFactory is usually a dependency injection container like Spring, Pico and Guice.

To define Guice as the ObjectFactory of our Struts 2 application we have to set the struts.objectFactory property to guice in the struts.xml file and Guice will then be responsible for instantiating all the Struts managed objects (actions, interceptors, etc) .

To continue add the following lines in struts.xml.

<!-- Use Guice as the ObjectFactory for this application -->
<constant name="struts.objectFactory" value="guice" />
<!-- When wiring actions use Guice bindings defined in the below module -->
<constant name="guice.module" value="com.tzavellas.dates.web.EjbModule"/>

11. Code the EjbModule

In the above struts.xml we defined two properties, struts.objectFactory and guice.module. To explain the guice.module property and the concept of Guice modules we have to explain the basics of Guice.

Guice is a, Java 5 based, dependency injection container that does constructor, field and setter injection (Guice also has features like support for AOP Alliance interceptors that we are not going to talk about in this post). To configure Guice you create a set of modules. A module implements the interface and contains bindings. Bindings are created with the that is passed to the configure(Binder) method of a module. A binding is a pair composed of a type (key) and an implementation. An implementation can be an object, a class or a provider (factory). The bindings are consulted by the Guice Injector when doing dependency injection.

In the Guice Struts 2 plug-in the Guice ObjectFactory creates an Injector that then reads the module from the guice.module property in the struts.xml file and uses the bindings that are specified in that module to do dependency injection in Struts 2 actions and interceptors.

All we have to do to enable our EJB to be injected into an action is to create a binding for the client interface of the bean. We can’t create a binding to a class or instance, because the EJB’s instances must be instantiated by the EJB container and not by Guice, so we will use a provider that will lookup the EJB from JNDI. The Guice library includes a JNDI provider that we are going to use that it is located in the class.

The below code is the implementation of the EJBModule, which has only two bindings. The first binds the javax.naming.Context type to the javax.naming.InitialContext implementation. This means that when the Guice Injector finds a field or parameter of type javax.naming.Context, that needs to be injected (marked with the @Inject annotation), it will create a new object of type javax.naming.InitialContext and inject it. This binding is needed by the JNDI provider that we are going to use in the next binding.

The second binding binds our EJB’s remote interface to the JNDI provider. The JNDI provider is returned from the call to the static JndiIntegration.fromJndi(Class, String) method. To get a JNDI provider we have to specify the expected class and JNDI name. This binding tells the Guice Injector that when it finds a field or parameter of type com.tzavellas.dates.ejb.DatesManagerRemote, that needs to be injected (marked with the @Inject annotation), it should call the provider’s get() method to retrieve an instance to inject.

package com.tzavellas.dates.web;
import static;
import com.tzavellas.dates.ejb.DatesManagerRemote;
import javax.naming.Context;
import javax.naming.InitialContext;

public class EjbModule implements Module {

  public void configure(Binder binder) {
    // Bind Context to the default InitialContext.
    // Bind the remote interface to the JNDI name using the JNDI Provider
          .toProvider(fromJndi(DatesManagerRemote.class, "com.tzavellas.dates.ejb.DatesManagerBean"));

For more information on how to do dependency injection with Guice see the Guice User’s Guide.

12. Change the action to use the EJB

Now that Guice instantiates our actions we can use the normal Guice @Inject annotation to mark an injection point in the action class. We can use any of the constructor, setter and field injection mechanisms. The below code uses field injection because it might be more familiar to EJB3 developers.

package com.tzavellas.dates.web;
import com.opensymphony.xwork2.ActionSupport;
import com.tzavellas.dates.ejb.DatesManagerRemote;
import java.util.Date;

public class CurrentDateAction extends ActionSupport {
  // Guice field injection of the SLSB
  @Inject DatesManagerRemote bean;

  private Date currentDate;

  public String execute() throws Exception {
    currentDate = bean.currentDate();
    return SUCCESS;

  public Date getCurrentDate() {
    return currentDate;


We are done. We’ve just coded a simple Struts 2 application that uses Guice to inject stateless session EJB3s to Struts actions. You can follow the instructions outlined above to do the same into your applications.

Appendix: Quick summary of all the steps

Assuming that you have a working Struts 2 application, below you will find a series of steps you could follow to do dependency injection of your stateless EJB3s into your Struts 2 actions.

For your project:

  1. Include the Guice jars in the WEB-INF/lib directory.
  2. Define a Guice module that will contain the bindings for your EJBs.
  3. Edit the struts.xml to define Guice as your ObjectFactory and include the above module.

For every EJB that you want to inject into your Struts actions:

  1. Inside the module, define a binding for the EJB using the Guice Provider from class, by specifying the bean’s client interface and the global JNDI name of the bean (or an ejb-ref if you have one defined in web.xml).
  2. Use the @Inject annotation in the Struts actions where you want the EJBs injected.

C# Extension methods

Scott Hanselman has a post about a user who doesn’t get what is cool about Ruby.

In the post you can find the below example that compares Java and Ruby in terms of code readability.

The Java code:

new Date(new Date().getTime() - 20 * 60 * 1000)

The Ruby code:


The article was interesting but what really caught my attention was some comments from C# programmers who showed how, in a few lines of code, you can mimic the Ruby syntax in C# using extension methods.

The new version of C#, shipped with the Orcas release of Visual Studio, has a new feature called extension methods. Extension methods were added to the .Net languages to support LINQ and they provide a way to attach methods to classes without changing their code.

The below code is copied and modified from the comments of Ian Cooper in the aforementioned blog post.

public static class TimeExtensions {

  public static TimeSpan Minutes(this int numberOfMinutes) {
    return new TimeSpan(0, numberOfMinutes, 0);

  public static DateTime Ago(this TimeSpan numberOfMinutes) {
    return DateTime.Now.Subtract(numberOfMinutes);

In the above code we defined a class, called TimeExtensions, which contains two extension methods. Notice the this keyword on the left of the fist parameter (both methods take one parameter in the example code) of the methods. The this keyword tells the C# compiler that a method is an extension method. The parameter annotated with the this keyword is the object on which the extension method is called. If I am correct, the methods are not really added to the classes (you can’t find them via reflection), the compiler at-compile-time translates them into static method calls.

In our example the first method, called Minutes, will be added to the int class (probably via auto-boxing) and the second method, called Ago, will be added to the TimeSpan class.

Now, to use the extension methods that we defined above we have to import them using the using TimeExtensions statement. This is a really good thing since the usage of extension methods is always explicit. You have to import them to use them and if you don’t want to use them you don’t import them.

using System;
using TimeExtensions;

public class HelloWorld {
  public static void Main() {
    Console.WriteLine( 20.Minutes().Ago() );

20.Minutes().Ago() is pretty close to 20.minutes.ago 🙂

For a nice tutorial about C# 3.0 extension methods see: New “Orcas” Language Feature: Extension Methods.

Making Maven 2 work with JUnit 4

The current stable version (2.2) of the maven-surefire-plugin does not support JUnit 4. So Maven, out of the box, does not work with JUnit 4. Luckily if we want to use JUnit 4 in our Maven based projects we have two choices. The first is to use JUnit4TestAdapter as illustrated in this post. The second is to use the snapshot version (2.3-SNAPSHOT) of the maven-surefire-plugin that has support for JUnit 4. In a small pet-project I am currently implementing I chose the second option and so far my experience was without any problems.

To use the 2.3-SNAPSHOT you first have to add the Maven snapshot plugin repository into your list of plugin repositories. In your pom.xml add the below XML:

    <name>Maven Plugin Snapshots</name>

You can also put this configuration into your ~/.m2/settings.xml file to enable this repository for all your projects.

Then go to the maven-surefire-plugin configuration section and change the version from 2.2 to 2.3-SNAPSHOT. For example below I have the maven-surefire-plugin configuration that I use in my pet-project:


That’s it, you are done. When you run Maven again the new (2.3-SNAPSHOT) version will be downloaded and you can start using JUnit 4 in you project.