首页 > 其他分享 >Netty中的handler类,通过@Autowired注入的类显示为Null

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

时间:2022-11-27 13:00:22浏览次数:39  
标签:Netty Autowired getBean scriptService handler static applicationContext public

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

 

标签:Netty,Autowired,getBean,scriptService,handler,static,applicationContext,public
From: https://www.cnblogs.com/javalinux/p/16929478.html

相关文章