如何用Guice注入Hk2豆

问题描述 投票:0回答:1

[有一个dropwizard应用程序,它基于球衣。我将Hk2 bean定义重写为Guice,现在可以将Guice bean注入Jersey资源,但我注意到在dropwizard软件包中定义的Hk2 bean无法重写由Guice可见,并且它无法注入Hk2中定义的依赖项。Guice看不到Hk2捆绑包中定义的bean,并且Guice默认情况下会创建新的未初始化bean。我通过requireExplicitBindings禁用了此行为。

我尝试使用HK2IntoGuiceBridge,但没有对我感兴趣的bean调用其匹配器。ConfiguredBundleX位于外部工件中。

[我试图从包中复制和转换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());
 }
java guice dropwizard hk2
1个回答
0
投票

[不幸的是,在Guice bean中,必须使用@ HK2Inject而不是@Inject才能将hk2 bean注入Guice。因此,在上面的代码中,您将执行以下操作:

public class DependsOnHk2Bean { @HK2Inject public DependsOnHk2Bean(MyHk2Bean b) {} }

这是由于guice的限制(目前可能已解决),因此@Inject行为无法被覆盖

我自己还没有尝试过上面的代码,所以我不确定它是否可以工作,但这是在编写桥时收回的价格...

© www.soinside.com 2019 - 2024. All rights reserved.