DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. WebSocket and CDI Integration. Again.

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.

Abhishek Gupta user avatar by
Abhishek Gupta
CORE ·
Nov. 21, 16 · Tutorial
Like (2)
Save
Tweet
Share
7.26K Views

Join the DZone community and get the full member experience.

Join For Free

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).
CDI WebSocket Integration

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Boot, Quarkus, or Micronaut?
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Tracking Software Architecture Decisions
  • 5 Software Developer Competencies: How To Recognize a Good Programmer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: