Tomcat8 WebSockets (JSR-356) with Guice 3.0

I am trying to @ Enable the Guice service in @ServerEndpoint. I am using Tomcat 8.0.15 as an implementation of JSR-356. However, dependency injection does not work. Is there any additional configuration that needs to be done in order to enable Guice injection? Please note that I use only standard javax annotations.

+5
source share
2 answers

I get it. The Websocket endpoint must have a custom configurator that creates and returns instances using the Guice injector instance.

Example:

Guice servlet custom context listener:

public class CustomServletContextListener extends GuiceServletContextListener { public static Injector injector; @Override protected Injector getInjector() { injector = Guice.createInjector(...); return injector; } } 

User configurator Websockets:

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

And then at the endpoint of the Websocket:

 @ServerEndpoint(value = "/ws/sample_endpoint", configurator = CustomConfigurator.class) public class SampleEndpoint { private final SomeService service; @Inject public SampleEndpoint(SomeService service) { this.service = service; } ... } 
+6
source

Based on Arithraโ€™s own answer:

Honestly, I don't know for sure if this works with Guice 3.0, but it works for 4.0, which is the current stable version.

I think a slightly cleaner approach is to change my CustomConfigurator to something like this:

 public class CustomConfigurator extends Configurator { @Inject private static Injector injector; public <T> T getEndpointInstance(Class<T> endpointClass) { return injector.getInstance(endpointClass); } } 

And then from the extended ServletModule class' configureServlets method call requestStaticInjection(CustomConfigurator.class)

Thus, you will not expose the injector to everyone. I donโ€™t know about you, but it gives me a pleasant and fuzzy feeling inside, to know that no one can bother with their injector :-).

+3
source

Source: https://habr.com/ru/post/1209202/


All Articles