由于某些原因,CDI似乎无法将字符串注入WebSocket ServerEndpoint。我收到错误Unsatisfied dependencies for type String with qualifiers @HelloMessage
。我在下面包含了Producer和ServerEndpoint实现。有任何想法吗?如果我创建一个自定义类(比如Messenger)并生成而不是String,那么注入似乎有效。
限定符实施
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
{
}
制片人实施
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;
}
答案 0 :(得分:1)
在定义制作人时,我需要导入javax.enterprise.inject.Produces
而不是javax.ws.rs.Produces
。
制片人实施
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!";
}
}