Table of Contents
As required in Java API for WebSocket, Tyrus supports full field, method and constructor injection using jakarta.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 jakarta.ejb.Stateful
,
jakarta.ejb.Singleton
and jakarta.ejb.Stateless
annotations are supported.
The following example presents how to inject a bean to the jakarta.websocket.server.ServerEndpoint
annotated class using jakarta.inject.Inject
. Class InjectedSimpleBean
gets injected
into class SimpleEndpoint
on line 15.
Example 7.1. Injecting bean into jakarta.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()); } }
The following sample presents how to turn jakarta.websocket.server.ServerEndpoint
annotated class
into jakarta.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(); } }