解決netty中spring對象注入失敗的問題
netty中spring對象注入失敗
今天在做項目的時候發(fā)現(xiàn)在netty中注入service失敗,百度許久后也找不到答案(@Component,@PostConstruct)未起作用,后靈光一現(xiàn)
發(fā)現(xiàn)了問題所在
如圖:
這些地方都必須通過spring注入才能實現(xiàn)其他依賴注入,之前這里都是采用new的,所以導致spring注入失敗
在netty中注入spring成份
前不久,在Netty中使用到數(shù)據(jù)庫數(shù)據(jù),由于Netty服務啟動后的上下文與 Spring的上下文不同,所以在Netty中獲取DAO數(shù)據(jù)很頭痛,無法使用@Autowired注入。
Aware本義就是"自動的",顧名思義Spring自動做了些事情。在此某些特殊的情況下,Bean需要實現(xiàn)某個功能,但該功能必須借助于Spring容器,此時就必須先獲取Spring容器,然后借助于Spring容器實現(xiàn)該功能。
為了讓Bean獲取它所在的Spring容器,可以讓該Bean實現(xiàn)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); } }
在使用時 可在某業(yè)務Handler中添加以下代碼:
private static NodeServService nodeServService;? static { ?? ?nodeServService = ToolNettySpirngAutowired.getBean(NodeServService.class); }? private static NodeJpaRepository nodeDao;? static { ?? ?nodeDao = ToolNettySpirngAutowired.getBean(NodeJpaRepository.class); }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Java的Hibernate框架數(shù)據(jù)庫操作中鎖的使用和查詢類型
這篇文章主要介紹了Java的Hibernate框架數(shù)據(jù)庫操作中鎖的使用和查詢類型,Hibernate是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2016-01-01