转载:https://blog.csdn.net/qq_29807745/article/details/82779884
作者在使用netty集成spring注入调用时普通的@Autowired一直bean注入为null,这里我只是记录针对netty注入spring无法注入bean的解决发放,具体底层实现,希望大神不吝赐教
首先上解决代码块,copy过去就可以直接用
@Component
public class NettyWebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
public static NettyWebSocketServerHandler nettyWebSocketServerHandler;
//1.正常注入[记得主类也需要使用@Component注解]
@Autowired
private IUserInfoService appUserService;
@Autowired
private IUserCoinRecordService userCoinRecordService;
//2.初始化构造方法一定要有
public NettyWebSocketServerHandler() {
}
//3.容器初始化的时候进行执行-这里是重点
@PostConstruct
public void init() {
nettyWebSocketServerHandler = this;
nettyWebSocketServerHandler.appUserService = this.appUserService;
nettyWebSocketServerHandler.userCoinRecordService = this.userCoinRecordService;
}
/**
* 管道初始化
*
* @param ctx
* @param msg
* @throws Exception
*/
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("收到消息: " + msg.text());
String info = DataParamsComm.analysisData(msg.text());
System.out.println("解密数据:" + info);
//4.这里是调用方法需要通过另一个bean去调用,你真正使用的bean
System.out.println(nettyWebSocketServerHandler.appUserService.findByUserId(500001L));
ctx.channel().writeAndFlush(new TextWebSocketFrame("接收到的内容: " + JSON.toJSONString(nettyWebSocketServerHandler.appUserService.findByUserId(500001L))));
}
}
这样就解决了spring整合netty无法注入bean的问题,现在bean在netty中正常的业务调用了