springboot遇见netty 获取配置文件参数值为null

近项目要对接设备通信接口,遇到一个奇葩问题【( ⊙ 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
————————————————
版权声明:本文为CSDN博主「龙小胖」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43706875/article/details/111135059

posted @ 2021-04-16 15:54  疯子110  阅读(520)  评论(0编辑  收藏  举报