9

我正在尝试将 Guice 服务 @Inject 到 @ServerEndpoint 中。我使用 Tomcat 8.0.15 作为 JSR-356 实现。但是,依赖注入不起作用。为了启用 Guice 注入,是否需要进行任何其他配置?请注意,我只使用所有标准 javax 注释。

4

2 回答 2

8

我想通了。Websocket 端点需要有一个自定义配置器,它使用 Guice 注入器实例创建和返回实例。

例子:

自定义 Guice servlet 上下文监听器:

public class CustomServletContextListener extends GuiceServletContextListener { 
    public static Injector injector;

    @Override
    protected Injector getInjector() {
        injector = Guice.createInjector(...);
        return injector;
    }
}

Websockets 自定义配置器:

public class CustomConfigurator extends Configurator {
  @Override
  public <T> T getEndpointInstance(Class<T> clazz)
        throws InstantiationException {
    return CustomServletContextListener.injector.getInstance(clazz);
  }
}

然后在 Websocket 端点中:

@ServerEndpoint(value = "/ws/sample_endpoint", configurator = CustomConfigurator.class)
public class SampleEndpoint {
  private final SomeService service;

  @Inject
  public SampleEndpoint(SomeService service) {
    this.service = service;
  }
  ...
}
于 2015-01-19T18:59:03.977 回答
6

基于 Aritra 自己的答案:

老实说,我不确定这是否适用于 Guice 3.0,但它确实适用于 4.0,这是当前的稳定版本。

我认为一种更简洁的方法是将您的 CustomConfigurator 更改为如下所示:

public class CustomConfigurator extends Configurator {
    @Inject
    private static Injector injector;

    public <T> T getEndpointInstance(Class<T> endpointClass) {
        return injector.getInstance(endpointClass);
    }
}

然后从您的扩展ServletModule类的configureServlets方法中,调用requestStaticInjection(CustomConfigurator.class)

这样您就不会将注射器暴露给所有人。我不了解你,但它给了我一种美好而模糊的感觉,知道没有人能弄乱我的注射器:-)。

于 2015-08-17T14:48:17.343 回答