Chapter 7. Injection Support

As required in Java API for WebSocket, Tyrus supports full field, method and constructor injection using javax.inject.Inject into all websocket endpoint classes as well as the use of the interceptors on these classes. Except this, Tyrus also supports some of the EJB annotations. Currently javax.ejb.Stateful, javax.ejb.Singleton and javax.ejb.Stateless annotations are supported.

7.1. javax.inject.Inject sample

The following example presents how to inject a bean to the javax.websocket.server.ServerEndpoint annotated class using javax.inject.Inject. Class InjectedSimpleBean gets injected into class SimpleEndpoint on line 15.

Example 7.1. Injecting bean into javax.websocket.server.ServerEndpoint

public class InjectedSimpleBean {

    private static final String TEXT = " (from your server)";

    public String getText() {
        return TEXT;
    }
}

@ServerEndpoint(value = "/simple")
public class SimpleEndpoint {

    private boolean postConstructCalled = false;

    @Inject
    InjectedSimpleBean bean;

    @OnMessage
    public String echo(String message) {
        return String.format("%s%s", message, bean.getText());
    }
}


7.2. EJB sample

The following sample presents how to turn javax.websocket.server.ServerEndpoint annotated class into javax.ejb.Singleton and use interceptor on it.

Example 7.2. Echo sample server endpoint.

@ServerEndpoint(value = "/singleton")
@Singleton
@Interceptors(LoggingInterceptor.class)
public class SingletonEndpoint {

    int counter = 0;
    public static boolean interceptorCalled = false;

    @OnMessage
    public String echo(String message) {
        return interceptorCalled ? String.format("%s%s", message, counter++) : "LoggingInterceptor not called.";
    }
}

public class LoggingInterceptor {

    @AroundInvoke
    public Object manageTransaction(InvocationContext ctx) throws Exception {
        SingletonEndpoint.interceptorCalled = true;
        Logger.getLogger(getClass().getName()).info("LOGGING.");
        return ctx.proceed();
    }
}