解決netty中spring對象注入失敗的問題
netty中spring對象注入失敗
今天在做項目的時候發(fā)現(xiàn)在netty中注入service失敗,百度許久后也找不到答案(@Component,@PostConstruct)未起作用,后靈光一現(xiàn)
發(fā)現(xiàn)了問題所在
如圖:


這些地方都必須通過spring注入才能實現(xiàn)其他依賴注入,之前這里都是采用new的,所以導(dǎo)致spring注入失敗
在netty中注入spring成份
前不久,在Netty中使用到數(shù)據(jù)庫數(shù)據(jù),由于Netty服務(wù)啟動后的上下文與 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è)務(wù)Handler中添加以下代碼:
private static NodeServService nodeServService;?
static {
?? ?nodeServService = ToolNettySpirngAutowired.getBean(NodeServService.class);
}?
private static NodeJpaRepository nodeDao;?
static {
?? ?nodeDao = ToolNettySpirngAutowired.getBean(NodeJpaRepository.class);
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
String在棧中,StringBuffer在堆中!所以String是不可變的,數(shù)據(jù)是共享的。StringBuffer都是獨占的,是可變的(因為每次都是創(chuàng)建新的對象?。?/div> 2015-11-11
Mybatis-plus與Mybatis依賴沖突問題解決方法
,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧這篇文章主要介紹了Mybatis-plus與Mybatis依賴沖突問題解決方法2021-04-04
IDEA使用properties配置文件進行mysql數(shù)據(jù)庫連接的教程圖解
Properties類是 鍵和值均為字符串的可以永久存儲到文件中的key-value集合。這篇文章主要介紹了IDEA使用properties配置文件進行mysql數(shù)據(jù)路連接 ,需要的朋友可以參考下2018-10-10
Maven構(gòu)建SpringBoot集成MyBatis過程
文章介紹了如何使用Maven創(chuàng)建一個Spring Boot項目,并集成MyBatis,首先,配置Maven環(huán)境,然后在pom.xml中添加MyBatis依賴,配置數(shù)據(jù)庫連接信息,最后生成Mapper XML文件和DAO層代碼2024-11-11
Java C++題解leetcode1620網(wǎng)絡(luò)信號最好的坐標
這篇文章主要為大家介紹了Java C++題解leetcode1620網(wǎng)絡(luò)信號最好的坐標示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01最新評論

