1. 程式人生 > 其它 >springboot整合netty無法autowired依賴注入的問題

springboot整合netty無法autowired依賴注入的問題

因為在初始話netty的時候,handler是new出來的,沒有託給spring容器管理,所以無法依賴注入,解決方法也很簡單:
第一步:加@component

@Component
public class handler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

第二步,建立handler的靜態物件

 private static handler handler;

第三步:使用@PostConstruct初始化

 @PostConstruct
    //因為是new出來的handler,沒有託給spring容器,所以一定要先初始化,否則autowired失效
    public void init() {
        handler = this;
    }

最後,在要使用依賴注入的地方前面加一個handler.即可

handler.examFeign.FeignGetData(eId);

完整實列:

@Component
@RabbitListener(queues = "rtQueue")
public class handler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static handler handler;
    @Autowired
    examFeign examFeign;

    static {
        list = new ConcurrentHashMap<>();
    }
    @PostConstruct
    //因為是new出來的handler,沒有託給spring容器,所以一定要先初始化,否則autowired失效
    public void init() {
        handler = this;
    }
    //監聽訊息,定時傳送資料
    @RabbitHandler
    public void handler(String eId) throws Exception {
      Map map=handler.examFeign.FeignGetData(eId);
        
    }
    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }


    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        //代做刪除功能
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("有一個新的使用者加入---");
    }
}

轉自:https://www.codeleading.com/article/82763511153/