解决 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); //使用

原文地址:https://www.cnblogs.com/lykbk/p/sdfgdsfdgfw454544545454454.html