首页 > 解决方案 > 依赖注入不适用于@ClientEndpoint java

问题描述

有没有办法在这个 @ClientEndpoint 类中启用 cdi(仍然使用注释而不是编程端点类)?我正在使用 Wildfly 14 和 java 8。

这是创建会话的代码,将类名传递给“createConnection”方法:

@ApplicationScoped //TODO move this to be request scoped
public class SessionProducer {

@Produces
public Session getSession(InjectionPoint ip) {
        SessionAnnotation annotation = ip.getAnnotated().getAnnotation(SessionAnnotation.class);
        if(annotation != null) {
            Class clazz = annotation.clazz();
            String url = annotation.serverURL();
              WebSocketContainer webSocketContainer = ContainerProvider.getWebSocketContainer();
                try {
                    return webSocketContainer.connectToServer(clazz, new URI(url)); //<----------this is the line that uses the annotated class (clazz is a reference to the class)
                } catch (DeploymentException | IOException | URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        return null;    
    }   

/**
 * The destroy/disposer metho for the session
 * @param session
 */
public void close(@Disposes Session session) {

       try {
        session.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    }
}

这是带注释的端点类:

@ClientEndpoint
public class CryptoCompareWSClient {

@Inject
@CryptoCompare
private Event<String> cryptoCompareEvent; //<--------this is always null, no cdi happens

public CryptoCompareWSClient() {
    System.out.println("constructor");
    //cryptoCompareEvent = new Event();
}

@PostConstruct
public void init() {
    System.out.println("post construct"); //<---------this never gets called
}

@OnOpen
public void open(Session session) {
    //session.getAsyncRemote().sendText("SubAdd: { subs: ['0~Poloniex~BTC~USD'] }"  /*"test"*/);
    System.out.println("opened");
}


 @OnClose
public void close(Session session) {
    System.out.println("Session " + session + " closed");
}

 @OnError
 public void error(Throwable error) {
    System.out.println("Error: " + error.getMessage());
}

 @OnMessage
 public void message(String message, Session session) {
     System.out.println("Message");
     //cryptoCompareEvent.fireAsync(message);
 }
 }

有什么方法可以在启用的类中启用 cdi 吗?

谢谢。

标签: javajakarta-eewebsocketwildflycdi

解决方案


推荐阅读