Over a million developers have joined DZone.

WebSocket and CDI Integration. Again.

Turning an old article on its head, see how one dev sees WebSockets and CDI working together within the Java EE platform for dependency injection and more.

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

In one of my older blog posts, I had written about what does not work as far as WebSocket and CDI integration within the Java EE Platform. This one talks about what’s possible with CDI in terms of

  • Dependency injection
  • Interceptors

Before you dig in, here is a summary:

Feature Supported in EJB Annotated WebSocket endpoint ? Supported in Plain WebSocket endpoint ?
Inject CDI managed beans yes yes
Use CDI interceptors yes yes

DI Support

It is possible to inject CDI managed beans in WebSocket endpoints. All injection targets are supported i.e. field, constructor, method:

@RequestScoped //CDI annotation
public class CDIManagedBean {
....
}

@ServerEndpoint("/stocks/")
public class StockTracker {

  @Inject
  private CDIManagedBean cdiBean;
  
  @OnOpen
  public void onOpenCallback(Session s){
    cdiBean.doSomething(); //use injected instance
  }
}

// works with an EJB as well

@ServerEndpoint("/weather/")
@Stateless 
public class WeatherTracker {

  @Inject
  private CDIManagedBean cdiBean;
  
  @OnOpen
  public void onOpenCallback(Session s){
    cdiBean.doSomething(); //use injected instance
  }
}


Interceptor Support

You can use interceptors to implement cross-cutting concerns in for the business methods in your WebSocket endpoints:

//the interceptor binding

@Inherited
@InterceptorBinding
@Retention(RUNTIME)
@Target({METHOD, TYPE})
public @interface LoggerInterceptorBinding {}

//Implement our interceptor and bind it

@Interceptor
@LoggerInterceptorBinding
public class CDIBasedLoggingInterceptor {

    @AroundInvoke
    public Object log(InvocationContext ic) throws Exception {
        Object retVal = null;
        String clazz = ic.getTarget().getClass().getName();
        try {
            Logger.enter(clazz);
            retVal = ic.proceed();
        } catch (Exception e) {
            throw e;
        } finally {
            Logger.exit(clazz);
        }
        return retVal;
    }
}

//Apply the interceptor where needed (via the binding)

@ServerEndpoint("/chat/")
public class ChatEndpoint {

  @LoggerInterceptorBinding //binding the CDIBasedLoggingInterceptor
  @OnOpen
  public void onChatMsgRecieved {
    //....
  }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">
    
    <interceptors>
        <class>com.wordpress.abhirockzz.test.CDIBasedInerceptor</class>
    </interceptors>
</beans>


Good to Know

Now that you have an idea about how WebSockets work with CDI in terms of dependency injection and interceptors, here are some other points:

  • DI and interceptors are supported for both server and client endpoints running within a JavaEE container.
  • DI and interceptors are supported for both annotated and programmatic endpoints running within a JavaEE container.
  • Container managed injection features are not available to WebSocket endpoints, which override the container implemented initialization (using the ServerEndpointConfig.Configurator).

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
constructor ,cdi ,websocket ,java ,dependency injection

Published at DZone with permission of Abhishek Gupta, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}