【发布时间】:2017-07-17 23:32:18
【问题描述】:
我正在尝试找出适合我需要的 CDI 和最佳方法。
我有一个与普通 tcp 通信交互的服务(TcpServiceImpl)。现在这个服务有一些地方需要通知某人发生了什么事。对于这些信息,我有接口TcpConnection,需要将 CDI 注入到正确的实现中。另一个问题是服务TcpServiceImpl本身被注入到一个定期执行的作业(TcpConnectionJob)中,并调用该服务来做事。
这意味着服务TcpServiceImpl 将多次存在。每个都有它处理的另一个 tcp 连接,并且有另一个设备需要另一个驱动程序/协议注入接口TcpConnection。
让我展示参与此场景的三个元素:
这里是获得多个实现的接口:
public interface TcpConnection
{
/**
* Connected.
*
* @throws NGException the NG exception
*/
public void connected() throws NGException;
/**
* This method will send the received data from the InputStream of the connection.
*
* @param data the received data
* @throws NGException the NG exception
*/
public void received( byte[] data ) throws NGException;
/**
* Usable for the protocol to send data to the device.
*
* @param data the data to send to the device ( Will be converted to byte[] with getBytes() )
* @throws NGException the NG exception
*/
public void send( String data ) throws NGException;
/**
* Usable for the protocol to send data to the device.
*
* @param data the data to send to the device ( Will be send as is )
* @throws NGException the NG exception
*/
public void send( byte[] data ) throws NGException;
/**
* This method will inform the protocol that the connection got closed.
*
* @throws NGException the NG exception
*/
public void closed() throws NGException;
}
这里还有一个示例 sn-p,说明何时在我现有的服务中调用它:
public class TCPServiceImpl implements TCPService, Runnable
{
/** The callback. */
private TcpConnection callback;
private void disconnect()
{
connection.disconnect();
if ( !getStatus( jndiName ).equals( ConnectionStatus.FAILURE ) )
{
setStatus( ConnectionStatus.CLOSED );
}
/* TODO: Tell driver connection is closed! */
callback.closed();
}
}
下面是调用服务的类,然后需要为接口动态注入正确的实现。
public class TcpConnectionJob implements JobRunnable
{
/** The service. */
private TCPService service;
public void execute()
{
service.checkConnection( connection );
}
}
服务注入callback 必须与正确的“协议”或“驱动程序”的实现相关联,以转换数据或处理设备的逻辑。接口的多个驱动程序实现会有所不同,我需要注入正确的一个。该决定的限定词可以是设备的名称。现在我查看了以下链接:
Understanding the necessity of type Safety in CDI
How to use CDI qualifiers with multiple class implementations?
问题:
但我仍然不确定使用哪种方式/方法以及正确的方法是什么。任何帮助将不胜感激。
我的第一个想法是将我的界面复制到限定符界面并附加这个以输入限定符的可能性。这是个好主意吗?
【问题讨论】: