首页 > 编程技术 > java

解决netty中spring对象注入失败的问题

发布时间:2022-2-14 20:47 作者:felix飞

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);
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。 

原文出处:https://blog.csdn.net/TIANTIANDOUNITIAN/article/details/8276

标签:[!--infotagslink--]

您可能感兴趣的文章: