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

2022-07-18,,,,

目录

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

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

《解决netty中spring对象注入失败的问题.doc》

下载本文的Word格式文档,以方便收藏与打印。