Google Guice, Google Gin and Spring

636 views Asked by At

I am planning to improve an already written code, which is a GWT application and needs to be deployed on GAE.

The dependency Injection is taken care by Guice and Gin. I am wondering if I can use Spring at the back end.(which is kind of a strict requirement).

I have the client code working properly and sending requests to my server code, In the `Service' class which lies in the Server code, I want to do a Spring injection for DAO layer.

But unfortunately the DAO reference is null even if I do a @Autowired injection. This results in a NPE.

I am aware that you can only inject pring managed beans within a spring context. So I tried putting an annotation @Service on the server side class which is receiving the RPC request from the client code. The class looks something like below:

@Path(ResourcesPath.PERSON)
@Produces(MediaType.APPLICATION_JSON)
@Service
public class PersonResource {

private Logger logger;

@Autowired
PersonDAO dao;

@Inject
PersonResource(Logger logger) {
    this.logger = logger;
}
}

I am hoping for something like this

@Path(ResourcesPath.PERSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource {

private Logger logger;

@Inject
PersonResource(Logger logger) {
    this.logger = logger;
}
}

Thank you for your help. Please suggest me something which can solve this.

2

There are 2 answers

0
F. Geraerts On

To use the @Service annotation with your config spring you must configure your context like this

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans.xsd
     http://www.springframework.org/schema/context
     http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="org.example"/>

</beans>

Spring will scan the package to found component annotations.

If you use java 5+, you can use the java configuration like this:

@Configuration
@ComponentScan({"org.example"})
public class ExampleConfig {

....
}

See the doc Classpath scanning and managed components for more informations.

0
Olivier Tonglet On

You can do that by configuring the Spring context as mentioned above or explained in this nice tutorial.

Many libraries can help you integrate GWT RPC mechanism with Spring, i.e gwtrpc-spring or spring4gwt

Many more example can be found on the web.