解决netty中spring对象注入失败的问题
netty中spring对象注入失败
今天在做项目的时候发现在netty中注入service失败,百度许久后也找不到答案(@Component,@PostConstruct)未起作用,后灵光一现
发现了问题所在
如图:


这些地方都必须通过spring注入才能实现其他依赖注入,之前这里都是采用new的,所以导致spring注入失败
在netty中注入spring成份
前不久,在Netty中使用到数据库数据,由于Netty服务启动后的上下文与 Spring的上下文不同,所以在Netty中获取DAO数据很头痛,无法使用@Autowired注入。
Aware本义就是"自动的",顾名思义Spring自动做了些事情。在此某些特殊的情况下,Bean需要实现某个功能,但该功能必须借助于Spring容器,此时就必须先获取Spring容器,然后借助于Spring容器实现该功能。
为了让Bean获取它所在的Spring容器,可以让该Bean实现ApplicationContextAware接口。
可以通过以下方式
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
*
* @author shilei
*
* @time 2019年6月19日 下午5:17:50
*
* @desc Netty中注入 Spring Autowired
*/
@Component
public class ToolNettySpirngAutowired implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (ToolNettySpirngAutowired.applicationContext == null) {
ToolNettySpirngAutowired.applicationContext = applicationContext;
}
}
// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 通过name获取 Bean.
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
// 通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
// 通过name,以及Clazz返回指定的Bean
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}在使用时 可在某业务Handler中添加以下代码:
private static NodeServService nodeServService;
static {
nodeServService = ToolNettySpirngAutowired.getBean(NodeServService.class);
}
private static NodeJpaRepository nodeDao;
static {
nodeDao = ToolNettySpirngAutowired.getBean(NodeJpaRepository.class);
}以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Mybatis-plus与Mybatis依赖冲突问题解决方法
,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧这篇文章主要介绍了Mybatis-plus与Mybatis依赖冲突问题解决方法2021-04-04
IDEA使用properties配置文件进行mysql数据库连接的教程图解
Properties类是 键和值均为字符串的可以永久存储到文件中的key-value集合。这篇文章主要介绍了IDEA使用properties配置文件进行mysql数据路连接 ,需要的朋友可以参考下2018-10-10
Java C++题解leetcode1620网络信号最好的坐标
这篇文章主要为大家介绍了Java C++题解leetcode1620网络信号最好的坐标示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-01-01


最新评论