Spring Boot + Netty 中 @Autowired, @Value 為空解決


問題描述

使用 Spring Boot + Netty 新建項目時 Handler 中的 @Autowired, @Value 注解的始終為空值

解決方法

@Component // 1. 添加 @Component 注解
public class TestHandler extends ChannelInboundHandlerAdapter {

    private static TestHandler testHandler; // 2. 定義本類的靜態對象

    @Autowired
    TestService testService;

    @PostConstruct // 3. 添加 @PostConstruct 注解的方法
    public void init(){
        testHandler = this;
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        ByteBuf buf = (ByteBuf) msg;

        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);

        testHandler.testService.handlerMessage(bytes); // 4. 使用

    }

}

參考:Netty handler處理類無法使用@Autowired注入bean的解決方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM