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

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

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

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

解决方案

1、使用@PostConstruct注解

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tIsyCkP6-1649826757555)(G:\西电研究生\学长简历\项目经验总结.assets\image-20210928173236517.png)]

我们想在生成对象时完成某些初始化操作,而偏偏这些初始化操作又依赖于注入的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的生命周期。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值