解決 SpringMVC 非spring管理的工具類使用@Autowired注解注入DAO為null的問題


在SpringMVC框架中,我們經常要使用@Autowired注解注入Service或者Mapper接口,我們也知道,在Controller層中注入service接口,在service層中注入其它的service接口或者mapper接口都是可以的,但是如果我們要在我們自己封裝的一些類中或者說非controller普通類中使用@Autowired注解注入Service或者Mapper接口,直接注入是肯定注入不成功的,當我們遇到這樣的問題,我們就要想辦法解決了。

//Component注解不用解釋了吧
@Component
public class MyTest {

@Autowired
private ItemService itemService;

@Autowired
private ItemMapper itemMapper;

//這個地方先聲明一下
public static MyTest myTest;

//init方法照寫就行了,一定不能少
@PostConstruct
public void init() {
myTest = this;
}

//其他地方需要使用就可以按照下面的方法調用就可以了
public static void test(Item record){
myTest.itemMapper.insert(record);
myTest.itemService.save();
}
}

 

demo2:

代碼截取:

@Component
@ServerEndpoint("/websocket/{nowUid}")
public class WebSocketTest {

@Autowired
private ShareDao shareDao;
//...省略
//靜態初始化
public static WebSocketTest webSocketTest;
//保證Bean初始化前已經裝配了屬性
@PostConstruct
public void init() {
webSocketTest = this;
}
//...
webSocketTest.shareDao.addToChatLog(nowUid, toUid, message, 1); //使用

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM