我已經研究過SO的大部分帖子,但沒有一個真的有幫助。我在使用spring bean訪問DAO的同時獲得了NPE。在Quartz工作中訪問spring bean
我的計劃
@Repository
@Transactional
public class JobSchedulerImpl implements IJobScheduler {
Scheduler scheduler;
Trigger trigger;
JobDetail job;
public JobSchedulerImpl() {
super();
try {
scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
} catch (SchedulerException e) {
logger.error("Exception while starting the scheduler :{} ", e.getMessage());
}
}
@Override
public void runWeekly(String whichDay, String userName) throws Exception {
//whichDay = whichDay.substring(0, 3);
//String cornJobExpression = "0 07 16 ? * " + whichDay + " *";
logger.info("Running Weekly Job");
String cornJobExpression = "0 0/1 * 1/1 * ? *";
job = JobBuilder.newJob(RunWeeklyJob.class).withDescription("runWeeklyJob_" + userName)
.withIdentity(userName, "group_runWeekly").build();
trigger = TriggerBuilder.newTrigger().withIdentity("runWeeklyTrigger_" + userName, "group_runWeekly")
.withSchedule(CronScheduleBuilder.cronSchedule(cornJobExpression)).startNow().build();
scheduler.scheduleJob(job, trigger);
}
}
作業類
public class RunWeeklyJob implements Job {
public static final Logger logger = LoggerFactory.getLogger(RunWeeklyJob.class);
@Autowired
private IRunReport report;
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
//SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
JobDetail jobdetails = context.getJobDetail();
JobKey jobKey = jobdetails.getKey();
String name = jobKey.getName();
report.getReport();
logger.info("Context : {}", context.toString());
}
}
報表界面
public interface IRunReport {
public void getReport();
}
實施
@Repository
@Transactional
public class RunReport implements IRunReport{
@Autowired
private IGenericCRUDDao genericDao;
public void getReport()
{
System.out.println("genericDao" + genericDao);
User userObj = genericDao.getEntityById(User.class, 1);
System.out.println("userObj : " + userObj);
}
測試用例
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring/applicationContext.xml")
public class RunReportTest {
@Autowired
IJobScheduler jobScheduler;
@Test
public void test_A_AddClients() throws Exception {
jobScheduler.runWeekly("MONDAY", "Santosh");
Thread.sleep(70000);
}
}
我收到NPE在訪問的Spring bean genericDao運行計劃的作業時間。我試着SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
和其他建議的答案,但沒有運氣。有人可以幫助我在哪裏出錯。
是的,那已經在那裏。 – Santosh