亲测可用,使用netty时注解为空,三步解决
第一步,将Handler交给spring 管理 添加@Component
示例:
@Slf4j
@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
第二步,静态初始化
示例:
@Slf4j
@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
public static NettyServerHandler nettyServerHandler;
@Resource
private IConeRecordService coneRecordService;
@PostConstruct
public void init() {
nettyServerHandler = this;
nettyServerHandler.coneRecordService = this.coneRecordService;
// 初使化时将已静态化的testService实例化
}
第三步,引用,注意引用需要加前缀,注意注意!!!
/**
* 客户端发消息会触发
*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf msgBuf = (ByteBuf) msg;
byte[] bytes = new byte[msgBuf.readableBytes()];
msgBuf.readBytes(bytes);
// 16进制转码后的内容
String hexStr = HexUtil.encodeHexStr(bytes);
log.info("收到服务器 {} 初始消息: {}",getClientIp(ctx),hexStr);
// 16进制转 字符串
String decodeHexStr = HexUtil.decodeHexStr(hexStr);
log.info("服务器收到 {} 解码消息: {}",getClientIp(ctx), decodeHexStr);
// 这里需要加前缀,避免为空
nettyServerHandler.coneRecordService.addRecord(decodeHexStr);
ctx.flush();
}
OK,成功使用!!! 亲测。