views:

161

answers:

1

Hi all,

I've been tasked with converting an application which was developed by myself in the Waffle Framework using PicoContainer as a DI mechanism into our new "stack" which is to use Struts2 as a framework with Guice as the DI mechanism. Does anyone out there have any helpful pointers as to how to do this with minimal pain and at the same time getting the best out of both the new framework and DI mechanism?

Many thanks in advance.

+2  A: 

Right, I realise the question was a bit vague, but I did get it done in the end. The Waffle/Pico mechanism for DI utilises a class called a Registrar to set up the classes you want injected and their scope within the webapp. The example on their site is :

 public class MyRegistrar extends AbstractRegistrar {  

   public MyRegistrar(Registrar delegate) {  
     super(delegate);  
   }  

   public void application() {  
     register("helloworld", HelloWorldController.class);  
   }  
 }

This example shows an application-scoped class - for session and request scopes, you simply place them inside the relevant session() or request() methods.

With Struts2 and Guice, things are structured a little differently. Taking Guice first, it injects dependencies using the @Inject annotation above the constructor. The injection configuration is done via classes called Modules, which must override a method called configure() in order to bind interfaces to their classes - Google's example is given below.

public class BillingModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
    bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
    bind(BillingService.class).to(RealBillingService.class);
  }
}

Scoping is also configured in these modules. A Singleton is effectively an application-scoped class and can be specified like this:

bind(TransactionLog.class).to(InMemoryTransactionLog.class).in(Singleton.class);

But Guice also has SessionScoped.class and RequestScoped.class so the transition is fairly trivial.

Regarding Struts2, the dependency injection used there was in fact an early version of what eventually became Guice, so it becomes a question of adding this line to struts.xml

<constant name="struts.objectFactory" value="guice" />

And specifying the StrutsPrepareAndExecuteFilter in the web.xml

<filter>         
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class>
</filter>     
<filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/* </url-pattern>
</filter-mapping>

That should be enough to get anyone with a similar setup issue started.

TuRRIcaNEd