项目场景:
项目使用SpringBoot框架开发,由于项目需要进行主动控制前端页面,项目中加入了Netty框架+WebSocket
问题描述:
代码中有个属性成员使用了@Autowired
进行自动注入。发现一直无法注入进去:
示例代码如下:
public class WebSocketURIHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Autowired
private NettyProperties nettyProperties;
xxxxxxx..........................
}
debug结果如下:
原因分析:
这里是因为这个类本身是被 new 的方式产生的,自动注入会失效。
完整概述:
若类A中包含成员属性B,B是通过@Autowired自动注入,而类A的实例是通过new的方式产生的,则自动注入会失效的。
用new的话,默认调用的是构造方法, 但是Autowired所注入的对应并没有被初始化。都是要Autowired注入的话,项目一启动就纳入spring容器的管理。
解决方案:
成员属性在类初始化的时候,进行赋值。
示例代码:
public class WebSocketURIHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private NettyProperties nettyProperties;
public WebSocketURIHandler(){
nettyProperties = (NettyProperties) SpringContextUtil.getBean("nettyProperties");
}
}