Tomcat8 WebSockets(JSR-356)与Guice 3.0

时间:2014-12-16 07:43:50

标签: java websocket guice tomcat8 jsr356

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

2 个答案:

答案 0 :(得分:8)

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

示例:

Custom 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;
  }
  ...
}

答案 1 :(得分: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)

这样你就不会将注射器暴露给每个人。我不了解你,但它让我感觉内心很好,模糊,知道没有人能用我的注射器弄乱: - )。

相关问题