多线程任务中,我是用@Autowired时,一直报空指针异常,说明不能自动注入bean
正文
我的临时解决方法是,将需要的bean当成成员变量,在线程管理中设置变量
MySynTask.java
import com.hundsun.rdm.dbclient.service.ITableOperateService;
import com.hundsun.rdm.dbserver.api.bean.entity.DbSynlog;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Data
public class MySynTask implements Runnable {
private final Logger logger = LoggerFactory.getLogger(MySynTask.class);
private DbSynlog dbSynlog;
private ITableOperateService iTableOperateService;
@Override
public void run() {
try {
String log = iTableOperateService.synInfo(dbSynlog).getSynResult();
logger.info(log);
} catch (Exception e) {
e.printStackTrace();
logger.error("---服务器错误---");
}
}
}
线程管理部分代码
MySynTask mySynTask = new MySynTask();
mySynTask.setDbSynlog(mySlaveClient.getDbSynlog(i));
mySynTask.setITableOperateService(iTableOperateService);
这也是一种方法,可以正常运行;趁着这次机会可以复习手动获取bean的知识。