springboot netty @Autowired @Resource service注解为空的问题

亲测可用,使用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,成功使用!!! 亲测。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值