1. 程式人生 > 其它 >springboot遇見netty 獲取配置檔案引數值為null

springboot遇見netty 獲取配置檔案引數值為null

技術標籤:spring bootnettyjava

在這裡插入圖片描述
最近專案要對接裝置通訊介面,遇到一個奇葩問題【( ⊙ o ⊙ )啊!】

springboot整合netty建立長連線整合機制,需要獲取配置檔案中的引數值,但始終為Null。。。。。

我們都知道,springboot獲取配置檔案引數值有多種方法,@Value最常用最常見,也可以引用Environment物件獲取。

配置檔案資料

在這裡插入圖片描述

失敗方式

正常方式取不到值

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.util.CharsetUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component; /** * @Author swd * @Create 2020/12/13 0013 16:56 * <p> * 注:正式使用中不需要實現Runnable介面,此處是為了啟用方便 */ @Component public class TestNettyServerHandler extends SimpleChannelInboundHandler implements Runnable { @Value("${test.no}") private
String no; @Autowired private Environment env; @Override public void run() { System.out.println("---------------------------------"); System.out.println("@Value方式獲取到的num值是:" + no); System.out.println("注入bean[Environment]獲取到的num值是:" + env.getProperty("test.no")); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { try { //區分是response 還是 request if (msg instanceof FullHttpRequest) { FullHttpRequest httpRequest = (FullHttpRequest) msg; // 請求uri String requestUri = httpRequest.uri(); // 訊息體內容 String content = httpRequest.content().toString(CharsetUtil.UTF_8); // 其他請求資訊暫未處理,直接透傳到後面可自定義的 handle ctx.fireChannelRead(msg); } else if (msg instanceof FullHttpResponse) { //平臺請求,裝置的回覆訊息 FullHttpResponse response = (FullHttpResponse) msg; // HttpResponseFactory.responseHandle(ctx, response); } else { ctx.fireChannelRead(msg); } } catch (Exception e) { e.printStackTrace(); } } }

結果顯而易見,拿不到O__O "…
在這裡插入圖片描述

正確開啟方式

  • 1、類上新增 @Component 註解
  • 2、定義本類的【靜態】物件,一定是靜態!
  • 3、新增 @PostConstruct 註解,自定義初始化方法
  • 4、就可以呼叫了 -->OK
	// 覆蓋上面程式碼中相同的方法
	// 1.新增 @Component 註解已有
 	private static TestNettyServerHandler testServerHandler; // 2.定義本類的靜態物件

    @PostConstruct // 3. 新增  @PostConstruct 註解 自定義初始化方法
    public void init() {
        testServerHandler = this;
    }

    @Value("${test.no}")
    private String no;

    @Autowired
    private Environment env;

    @Override
    public void run() {
        System.out.println("---------------------------------");
        System.out.println("@Value方式獲取到的num值是:" + testServerHandler.no); // 4.呼叫
        System.out.println("注入bean[Environment]獲取到的num值是:" + testServerHandler.env.getProperty("test.no"));// 4.呼叫
    }

成功獲取【喜大普奔。。】
在這裡插入圖片描述
程式碼示例注入bean是自帶的Environment ,也可以注入自定義自行定義的bean資料,完美解決取值為Null的問題。
感謝O(∩_∩)O

文章連結:https://www.cnblogs.com/victorbu/p/10692867.html