Netty中的handler类,通过@Autowired注入的类显示为Null
Netty中的handler类,通过@Autowired注入的类显示为Null

原因:netty中无法使用注入的bean,需要主动通过getBean的方式来获取。并不是配置的问题,而是因为netty启动的时候并没有交给spring IOC托管。

解决方案
1、使用@PostConstruct注解
方法上加该注解会在项目启动的时候执行该方法,即spring容器初始化的时候执行,它与构造函数及@Autowired的执行顺序为:构造函数 >> @Autowired >> @PostConstruct。

 

 

我们想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于注入的bean,那么就无法在构造函数中实现,为此可以使用@PostConstruct注解一个init方法来完成初始化,该方法会在bean注入完成后被自动调用。

@Autowired
ScriptService scriptService;

public static MqttSeverHandler mqttSeverHandler;

@PostConstruct
public void init(){
mqttSeverHandler = this;
mqttSeverHandler.scriptService = this.scriptService;
}
 
2、使用SpringUtil
package com.example.Util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringUtils implements ApplicationContextAware {

private static ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtils.applicationContext == null){
SpringUtils.applicationContext = applicationContext;
}
}

public static ApplicationContext getApplicationContext(){
return applicationContext;
}

public static Object getBean(String name){
return getApplicationContext().getBean(name);
}

public static <T> T getBean(Class<T> clazz){
return getApplicationContext().getBean(clazz);
}

public static <T> T getBean(String name, Class<T> clazz){
return getApplicationContext().getBean(name, clazz);
}
}
 
使用

@Slf4j
@RequiredArgsConstructor
@Service
@ChannelHandler.Sharable
public class MqttSeverHandler extends SimpleChannelInboundHandler<MqttMessage> {
public static Map<ChannelHandlerContext, JSONObject> sublist=new HashMap<>();
public static Map<String,List<ChannelHandlerContext>> topiclist =new HashMap<>();

public static MqttSeverHandler mqttSeverHandler;
private static ScriptService scriptService;
static {
scriptService = SpringUtils.getBean(ScriptServiceImpl.class);
}
 
总结
主要Spring Bean的生命周期。

————————————————
版权声明:本文为CSDN博主「v_BinWei_v」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/ohwang/article/details/124145678

 

原文地址:http://www.cnblogs.com/javalinux/p/16929478.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性