线程是安全的,线程中不能够直接注入bean,会直接报空指针错误。
解决方案:
1.创建一个工具类,直接粘贴到文件里就可以
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanContext.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext(){
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T)applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clz) throws BeansException {
return (T)applicationContext.getBean(clz);
}
}
2.在线程中通过工具类调用,其他的bean也可以这样用
public class MyThread implements Runnable {
private ClientMapper clientMapper;
@Override
public void run(){
//调用
clientMapper = BeanContext.getApplicationContext().getBean(ClientMapper.class);
ClientInfo clientInfo = new ClientInfo();
clientInfo.setProgramStatus(PowerState.powerOn);
//可以使用mapper
List<ClientInfo> clientInfos = clientMapper.onLineList(clientInfo);
}
}