在 Quartz 作业中访问 spring 个 bean

Access spring bean in Quartz job

我已经研究了 SO 上的大部分 post,但 none 这确实有帮助。我在使用 spring bean 访问 DAO 时收到 NPE。

我的日程安排程序

@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);

     } 
}

工作Class

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);
}
}

我在访问 spring bean genericDao 时收到 NPE,而 运行 计划作业。我在 SO 上尝试了 SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 和其他建议的答案,但没有成功。有人可以帮助我哪里出错了。

检查是否在您的配置中指定了包扫描组件。 例如:

<context:component-scan base-package="your.package.here" />

Spring 阅读它以扫描注释。

这是 spring 安全性不允许我在 Web 上下文之外注入 bean。一旦我设置了权限,它就会按预期工作。

有趣的事情 none of exception 提供了有关安全相关消息的任何线索。