Loading Spring Context from Google Guice
Using Spring framework in any application opens a plethora of opportunities with regard to resolving complex requirement needs in lieu of the number of extensible components available based on the Spring framework. Some of the most preferred specification based stacks (such as Apache CXF) are coupled with Spring Framework, and it would call for a need to figure out options of getting the best of breed application stacks.
This particular entry looks at loading Spring Framework from Google Guice container. There are two approaches I have across till now, which I will try covering in breif:
1) Using Guice’s SpringIntegration
In this approach you need to download guice-spring.jar (version 1.0) or if your project is maven based, add the following dependency.
<dependency>
<groupId>com.google.inject.integration</groupId>
<artifactId>guice-spring</artifactId>
<version>1.0</version>
</dependency>
You need to generalize an AbstractModule and use the com.google.inject.spring.SpringIntegration to load the Spring context into the Guice’s container.
import com.google.inject.spring.SpringIntegration;
import com.google.inject.AbstractModule;
//other imports...
public class SpringContextModule extends AbstractModule
{ @Override
protected void configure()
{ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appcontext-config.xml");
SpringIntegration.bindAll(binder(), applicationContext);
}
}
2) Using GuiceyFruit’s SpringModule
In this approach, the dependency injection is based on JSR-250 common annotations specification and is resolved using the Spring annotation @Autowired (i.e.) all the beans have to be modified, introducing the annotation wherever the injection is required. This approach is suitable for all the beans for which we have control on the source code, and may not be a viable option for integration proven Spring modular components. In case if you have maven project, you need to include the below dependency:
<dependency> <groupId>org.guiceyfruit</groupId> <artifactId>guiceyfruit-spring</artifactId> <version>2.0-beta-6</version> </dependency>
and create a Guice injector using
Injector injector = Guice.createInjector(new SpringModule());
More details can be looked at Guicey-Spring integration wiki page.
Approach 1 is prefered for integration of various most commonly used module component common both between Guice and Spring, as the configuration context can be reused, while the other approach is good enough for custom modules in Spring to be injected in Google Guice.