调用代码(片断)
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);即可,如下图