java反射調用方法時@Autowired注入的屬性爲空

調用代碼(片斷)

        // 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);即可,如下圖

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章