【问题标题】:Tomcat8 WebSockets (JSR-356) with Guice 3.0带有 Guice 3.0 的 Tomcat8 WebSockets (JSR-356)
【发布时间】:2015-02-14 11:29:48
【问题描述】:

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

【问题讨论】:

  • “依赖注入不起作用”...你能更详细地描述一下吗?
  • 当我尝试在 SeverEndpoint 中使用 @Inject 进行构造函数注入时,我得到一个实例化异常。

标签: java websocket guice tomcat8 jsr356


【解决方案1】:

我想通了。 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;
  }
  ...
}

【讨论】:

    【解决方案2】:

    基于 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)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-18
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      相关资源
      最近更新 更多