1
votes

For some reason CDI seems unable to inject a string into a WebSocket ServerEndpoint. I am receiving the error Unsatisfied dependencies for type String with qualifiers @HelloMessage. I've included the Producer and ServerEndpoint implementations below. Any ideas? Injection seems to work if I create a custom class (say Messenger) and produce that instead of String.

Qualifier Implementation

import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public
@interface HelloMessage
{
}

Producer Implementation

import java.io.Serializable;

import javax.inject.Named;
import javax.ws.rs.Produces;

public
class StringProducer
implements Serializable
{
    @Produces
    @HelloMessage
    public
    String getMessage()
    {
        return "Hello, from Message!";
    }
}

ServerEndpoint Implementation

import javax.inject.Inject;
import javax.inject.Named;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint(value = "/test")
public
class TestEndpoint
{
    @OnMessage
    public
    void onMessage(Session session, String unused)
    {
        System.out.println(this.message);
    }

    @Inject @HelloMessage
    private String message;
}
1

1 Answers

1
votes

I needed to import javax.enterprise.inject.Produces instead of javax.ws.rs.Produces when defining the Producer.

Producer Implementation

import java.io.Serializable;

import javax.inject.Named;
import javax.enterprise.inject.Produces;

public
class StringProducer
implements Serializable
{
    @Produces
    @HelloMessage
    public
    String getMessage()
    {
        return "Hello, from Message!";
    }
}