調用代碼(片斷)
Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(XxlJobHandler.class);
if (serviceBeanMap!=null && serviceBeanMap.size()>0) {
for (Map.Entry<String, Object> entry : serviceBeanMap.entrySet()) {
final Class<?> serviceClass = entry.getValue().getClass();
XxlJobHandler xxlJobHandler = serviceClass.getAnnotation(XxlJobHandler.class);
String name = xxlJobHandler.value();
String method = xxlJobHandler.method();
if (StringUtils.isEmpty(name)) {
name = entry.getKey();
}
if (loadJobHandler(name) != null) {
throw new RuntimeException("xxl-job jobhandler naming conflicts.");
}
IJobHandler handler = new IJobHandler() {
@Override
public ReturnT<String> execute(JobInitDto jobInitDto) throws Exception {
Method jobMethod = serviceClass.getMethod(method, JobInitDto.class);
jobMethod.invoke(serviceClass.newInstance(), jobInitDto);
return SUCCESS;
}
};
registJobHandler(name, handler);
}
}
目標代碼(片斷)
@XxlJobHandler(value="checkFileExistsJobHandler", method = "execute")
@Component
public class CheckFileExistsJobHandler {
private static Logger logger = LoggerFactory.getLogger(CheckFileExistsJobHandler.class);
private static final String JOB_NAME = ">>>>>>>>>> 第一步:檢查文件是否存在作業";
private List<AccountFileConfig> accountFileConfigs;
private String designatedDate;
@Autowired
private SftpHelper sftpHelper;
@Autowired
private AccountFileConfigDao accountFileConfigDao;
@Autowired
private SystemInfoService systemInfoService;
現象:java反射調用方法時@Autowired注入的屬性爲空
原因:class.newInstance()獲取得對象與Spring IOC容器無關,所以@Autowired無法關聯注入對象
解決方法:把jobMethod.invoke(serviceClass.newInstance(), jobInitDto);
改爲jobMethod.invoke(applicationContext.getBean(serviceClass), jobInitDto);
即可,如下圖