We have a Spring framework based application and need to integrate a component that is built using Google Guice.
Can anybody give us some advice on how this can be done?
We came across the following links that show how integrate Spring into Guice, but we need it the other way around:
http://google-guice.googlecode.com/git/javadoc/com/google/inject/spring/SpringIntegration.html
http://www.jroller.com/mindcrime/entry/an_example_of_integrating_guice
Any help is appreciated
No Special framework or dependency is required to integrate guice component into spring-boot.
standard boot app
@SpringBootApplication
public class App {
SpringApplication.run(App.class, appArgs);
}
Guice module config
@Configuration
public class GuiceBeanConfig {
private final Injector injector;
// guice modules are initialized before the spring context completes
{
injector = Guice.createInjector(
new MyModuleA(),
new MyModuleB()
);
}
/**
* Option1: can expose injector as a Spring Bean.
*/
@Bean
public Injector injector() {
return injector;
}
/**
* Option2: expose specific component as a Spring Bean.
*/
@Bean
public MyServiceA serviceA() {
return injector.getInstance(ServiceA.class);
}
}
Autowire into your service component as a regular spring bean.
Option1: autowire guice injector and access any bean from it
@Service
public class MySpringService {
private final ServiceA serviceA;
MySpringService (Injector i){
serviceA = injector.getInstance(ServiceA.class)
}
public void callServiceA() {
serviceA.doSomething();
}
}
Option2: autowire specific bean
@Service
public class MySpringService {
private final ServiceA serviceA;
MySpringService (ServiceA s){
serviceA = s;
}
public void callServiceA() {
serviceA.doSomething();
}
}
NOTE 1:
By default Spring uses scope: Singleton and guice: Prototype.
In case your guice component is not annotated as @Singleton :
Option1 creates an instance of ServiceA each time you create a new instance of MySpringService.
Option2 instead exposes ServiceA as a bean with scope Singleton.
Singleton vs Prototype: if you component/service is threadsafe, does not keep state the better option would be Singleton. Much better performance, less work for GC.
NOTE 2: Spring-boot does not require to use @Autowire annotation in case you do constructor injection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With