有一个dropwizard应用程序,它是基于jersey的。我将Guice bean定义重写到Hk2中,现在可以将Guice bean注入Jersey Resources,但是我注意到Hk2 bean在dropwizard捆绑包中定义,但我不能重写,它对Guice不可见,并且它无法注入Hk2中定义的依赖项。
Guice看不到Hk2包中定义的bean,默认情况下,Guice会创建新的未初始化bean。我用requireExplicitBindings禁用了这个行为。
我用HK2IntoGuiceBridge做过实验,但是我感兴趣的bean没有调用它的匹配器。ConfiguredBundleX位于外部工件中。
我试图从bundle中复制和翻译bean定义,并坚持使用jersey bean Provider<ContainerRequest>,我不知道它是从哪里来的。
public class ConfiguredBundleX implements ConfiguredBundle<MyAppConf> {
public void run(T configuration, Environment environment) throws Exception {
environment.jersey().register(new AbstractBinder() {
protected void configure() {
this.bind(new MyHk2Bean()).to(MyHk2Bean.class);
}
});
}
}
public class DependsOnHk2Bean { @Inject public DependsOnHk2Bean(MyHk2Bean b) {} }
public class MainModule extends AbstractModule {
private final ServiceLocator locator;
protected void configure() {
binder().requireExplicitBindings();
install(new HK2IntoGuiceBridge(locator));
bind(DependsOnHk2Bean.class);
}
public class GuiceFeature implements Feature {
public boolean configure(FeatureContext context) {
ServiceLocator locator = ServiceLocatorProvider.getServiceLocator(context);
GuiceBridge.getGuiceBridge().initializeGuiceBridge(locator);
Injector injector = Guice.createInjector(
new HK2IntoGuiceBridge(locator),
new MainModule(locator));
GuiceIntoHK2Bridge guiceBridge = locator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(injector);
return true;
}
}
// ...
public void initialize(Bootstrap<X> bootstrap) {
bootstrap.addBundle(new ConfiguredBundleX());
}
public void run(X config, Environment env) {
env.jersey().register(new GuiceFeature());
}发布于 2020-04-09 22:00:52
不幸的是,在Guice beans中,为了将hk2 bean注入Guice,您必须使用@HK2Inject而不是@Inject。因此,在上面的代码中,您将执行以下操作:
public class DependsOnHk2Bean { @HK2Inject public DependsOnHk2Bean(MyHk2Bean b) {} }这是因为guice中的限制(现在可能已经修复),@Inject行为不能被覆盖
我自己没有尝试过上面的代码,所以我不确定它是否可以工作,但这是桥编写时的交易……
发布于 2020-04-11 02:15:32
在研究了Guice和HK2ToGuiceTypeListenerImpl之后,我发现有一种bindListener可以拦截丢失的绑定,并将它们从某个地方提取出来。@HKInject代码在那里,但我注意到侦听器没有被调用某些bean,包括我感兴趣的bean。是的,HKInject不支持构造函数注入(4.2.1版本)
因此,我决定手动导入HK并将其绑定到Guice中。Dropwizard的术语是可怕的,有一些方法获取上下文,获取管理上下文是完全不同的东西,beans必须用getService方法获取!
@RequiredArgsConstructor
public class HkModule extends AbstractModule {
private final ServiceLocator locator;
@Override
protected void configure() {
binder().requireExplicitBindings();
Provider<Bar> barProvider = locator.getService(
new TypeLiteral<Provider<Bar>>(){}.getType());
bind(Bar.class).toProvider(barProvider);
bind(Foo.class).toInstance(locator.getService(Foo.class));
}
}https://stackoverflow.com/questions/61112126
复制相似问题