Quartz 定時任務執行 execute() 時,調用 Service 方法報 NullPointerException,pipeResAction 為 null。
配置文件中同一 Bean 定義了兩次(或父子上下文重複掃描),導致:
pipeResAction。StartupApp.getInstance().getAppContext().getBean("reportpiperesource") 從另一個上下文獲取 Bean,該上下文中該 Bean 未正確初始化/注入。<!-- 定時任務 Job -->
<bean class="com.boco.auto.AutoIPV6BusinessAlarmStatisticsReport"> ... </bean>
<!-- Action Bean 定義了兩次?不同 id 或父子上下文 -->
<bean id="reportpiperesource" class="com.boco.web.struts.action.report.ReportCommonActionPipeRes" parent="baseAction"> ... </bean>
<bean id="vendorFaultReportService" class="com.boco.alarm.service.impl.VendorFaultReportServiceImpl"> ... </bean>
<bean> 定義,或統一 id。@Autowired private ReportCommonActionPipeRes pipeResAction;,避免手動 getBean() 依賴上下文查找順序。ApplicationContextAware,在 setApplicationContext 中保存引用,而非依賴單例工具類 StartupApp。@Component
public class AutoAlarmStatisticsReport implements Job {
private static final Logger logger = LoggerFactory.getLogger(AutoAlarmStatisticsReport.class);
@Autowired
private ReportCommonActionPipeRes pipeResAction; // 直接注入
@Override
public void execute(JobExecutionContext context) {
logger.info("+++ 進入定時任務 +++");
generateReport();
}
private void generateReport() {
pipeResAction.insertBusinessNEStatistics("IPV6BusinessAlarmStatistics");
}
}
Spring 定時任務空指針多因上下文隔離或重複 Bean 定義導致依賴未注入。統一上下文、優先使用註解驅動注入、避免手動 getBean() 是根治之道。