示例错误代码:
package com.uniin.ib.provider.iot.handle;@Slf4j
@Component
public class FireStringInboundHandler extends ChannelInboundHandlerAdapter {@Autowiredprivate RsFireMonitoringMapper rsFireMonitoringMapper;@Autowiredprivate RsFireAlertMapper rsFireAlertMapper;@Autowiredprivate RedisUtils redisUtils;@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {log.info("远程地址: " + ctx.channel().remoteAddress());if (msg == null) {log.warn("fire接收到的消息为null,跳过处理");return;}// 这里需要调用redis的工具类,无法获取一直为null,报错误空指针redisUtils.set("redisKey", "testRedisValue",60*1L, TimeUnit.SECONDS);}}
通过查询发现类加了@Component注解后,并没有被spring容器纳入管理,没法正常注册为bean
需要在类加载初始化时,把引用到的对象手动加载init初始化,才能正常使用。
package com.uniin.ib.provider.iot.handle;@Slf4j
@Component
public class FireStringInboundHandler extends ChannelInboundHandlerAdapter {@Autowiredprivate RsFireMonitoringMapper rsFireMonitoringMapper;@Autowiredprivate RsFireAlertMapper rsFireAlertMapper;@Autowiredprivate RedisUtils redisUtils;// 注意点,这里需要使用静态private static FireStringInboundHandler stringInboundHandler;// 容器加载完成后,在执行init()方法初始化,不加注解无法正常调用(注意点)//这个方法会在依赖注入完成后被自动调用。这通常用于初始化代码,比如打开数据库连接或者启动一些服务。@PostConstructpublic void init() {stringInboundHandler= this;stringInboundHandler.redisUtils = this.redisUtils;stringInboundHandler.rsFireMonitoringMapper = this.rsFireMonitoringMapper;stringInboundHandler.rsFireAlertMapper = this.rsFireAlertMapper;}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {log.info("远程地址: " + ctx.channel().remoteAddress());if (msg == null) {log.warn("fire接收到的消息为null,跳过处理");return;}// 这里需要调用redis的工具类,无法获取一直为null,报错误空指针// 调用方式需要通过init初始化后才能用stringInboundHandler对象类去调用才能正常,不然报错空指针stringInboundHandler.redisUtils.set("redisKey", "testRedisValue",60*1L, TimeUnit.SECONDS);}}