我们有一个基于Spring框架的应用程序,需要集成使用Google Guice构建的组件.
有人可以就如何做到这一点给我们一些建议吗?
我们遇到了以下链接,展示了如何将Spring集成到Guice中,但我们需要反过来:
http://google-guice.googlecode.com/git/javadoc/com/google/inject/spring/SpringIntegration.html
http://www.jroller.com/mindcrime/entry/an_example_of_integrating_guice
任何帮助表示赞赏
将 guice 组件集成到 spring-boot 中不需要特殊的框架或依赖项。
标准启动应用程序
@SpringBootApplication
public class App {
SpringApplication.run(App.class, appArgs);
}
Run Code Online (Sandbox Code Playgroud)
Guice模块配置
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
作为常规 spring bean 自动装配到您的服务组件中。
选项1:自动装配 guice 注入器并从中访问任何 bean
@Service
public class MySpringService {
private final ServiceA serviceA;
MySpringService (Injector i){
serviceA = injector.getInstance(ServiceA.class)
}
public void callServiceA() {
serviceA.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)选项2:自动装配特定bean
@Service
public class MySpringService {
private final ServiceA serviceA;
MySpringService (ServiceA s){
serviceA = s;
}
public void callServiceA() {
serviceA.doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)注意1:默认情况下Spring使用scope: Singleton和 guice: Prototype。如果您的 guice 组件未注释为@Singleton:每次创建 MySpringService 的新实例时,
Option1都会创建 ServiceA 的实例。
选项 2将 ServiceA 公开为范围为 Singleton 的 bean。
单例与原型:如果你的组件/服务是线程安全的,不保持状态,更好的选择是单例。更好的性能,更少的 GC 工作。
注意 2:如果您进行构造函数注入,Spring-boot 不需要使用 @Autowire 注释。
Ric*_*lla -1
Spring 和 Guice 都支持JSR 330:Java 依赖注入。如果您需要的 Guice 组件是使用 JSR 330 注释定义的,或者您有权访问代码并可以更改注释,那么您应该能够在 Spring 托管 bean 中使用它。
请参阅Spring:使用 JSR 330 标准注释和Guice JSR-330 集成
| 归档时间: |
|
| 查看次数: |
2936 次 |
| 最近记录: |