调用代码(片断)
// init job handler action
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.");
}
// register jobhandler
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);即可,如下图

版权声明:本文为q283614346原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。