示例错误代码:
package com.uniin.ib.provider.iot.handle;
@Slf4j
@Component
public class FireStringInboundHandler extends ChannelInboundHandlerAdapter {
@Autowired
private RsFireMonitoringMapper rsFireMonitoringMapper;
@Autowired
private RsFireAlertMapper rsFireAlertMapper;
@Autowired
private RedisUtils redisUtils;
@Override
public 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 {
@Autowired
private RsFireMonitoringMapper rsFireMonitoringMapper;
@Autowired
private RsFireAlertMapper rsFireAlertMapper;
@Autowired
private RedisUtils redisUtils;
// 注意点,这里需要使用静态
private static FireStringInboundHandler stringInboundHandler;
// 容器加载完成后,在执行init()方法初始化,不加注解无法正常调用(注意点)
//这个方法会在依赖注入完成后被自动调用。这通常用于初始化代码,比如打开数据库连接或者启动一些服务。
@PostConstruct
public void init() {
stringInboundHandler= this;
stringInboundHandler.redisUtils = this.redisUtils;
stringInboundHandler.rsFireMonitoringMapper = this.rsFireMonitoringMapper;
stringInboundHandler.rsFireAlertMapper = this.rsFireAlertMapper;
}
@Override
public 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);
}
}