X
    Categories: Coding

GWTP, Guice and Spring non-trivial beans

Having struggled a bit with the somewhat terse documentation and JavaDoc I finally figured out the tricks of using Guice and GWTP along with Spring. As much for my own future reference and for others that may have the same issues, here’s what I did.

First we need to make Guice aware of our Spring configuration. For this we need the com.google.inject.extensions:guice-spring artifact

Also, it is vitally important that we explicitly autowire the beans apparently…

public class ServerModule extends HandlerModule
{
    @Override
    protected void configureHandlers()
    {
        // Bind spring beans to Guice
        final ClassPathXmlApplicationContext beanFactory = new ClassPathXmlApplicationContext( "applicationContext.xml" );
        AutowireCapableBeanFactory factory = beanFactory.getAutowireCapableBeanFactory();
        factory.autowireBeanProperties( this, AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT , true );

        // Must bind BeanFactory for fromSpring( ... , ... ) to work!
        bind( BeanFactory.class ).toInstance( beanFactory );
        bind( UserDao.class ).toProvider( fromSpring( UserDaoImpl.class, "userDao" ) ).in( Singleton.class );
    }
}

Once we have these bindings, we can go on injecting:

public class AuthenticateUserHandler extends BaseActionHandler<AuthenticateUserAction,AuthenticateResult>
{
    private UserDao userDao;

    @Inject
    public AuthenticateUserHandler( UserDao userDao )
    {
        super( AuthenticateUserHandler.class );
        this.userDao = userDao;
    }

    ...
}

Voila!

Anders Rostgaard Bystrup:
Related Post