如何在spring mvc控制器方法中调用bean。

时间:2015-06-12 13:22:42

标签: java spring quartz-scheduler

我有QuartzConfig配置类有三个bean,如何在spring mvc controller方法中调用这个bean。

这个bean在我启动应用程序后自动执行,但我不希望我想通过控制器执行这个bean

Quartz配置类

@Configuration
public class QuartzConfig {

@Autowired
private PlatformTransactionManager transactionManager;

@Autowired
private ApplicationContext applicationContext;

@Bean
public SchedulerFactoryBean quartzScheduler() {
    SchedulerFactoryBean quartzScheduler = new SchedulerFactoryBean();

    quartzScheduler.setTransactionManager(transactionManager);
    quartzScheduler.setOverwriteExistingJobs(true);

    AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
    jobFactory.setApplicationContext(applicationContext);
    quartzScheduler.setJobFactory(jobFactory);

    Trigger[] triggers = {
            processMyJobTrigger().getObject()
    };

    quartzScheduler.setTriggers(triggers);

    return quartzScheduler;
}

@Bean
public JobDetailFactoryBean processMyJob() {
    JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
    jobDetailFactory.setJobClass(HelloJob.class);
    jobDetailFactory.setDurability(true);
    return jobDetailFactory;
}

@Bean
public CronTriggerFactoryBean processMyJobTrigger() {
    CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
    cronTriggerFactoryBean.setJobDetail(processMyJob().getObject());
    cronTriggerFactoryBean.setCronExpression("0 0/1 * * * ?");
    return cronTriggerFactoryBean;
}

}

Quartz job

@Service
@Transactional
public class HelloJob implements Job{

@Inject
TestrecordRepository testrecordRepository;
@Inject
ScoreRepository scoreRepository;


public void execute(JobExecutionContext context)
        throws JobExecutionException {
            System.out.println("Hello Quartz!");    
            List<Testrecord> records=testrecordRepository.findAll();
            for(Testrecord t:records){
                Testrecord testrecord = new Testrecord();
                testrecord.setValue_integer(t.getValue_integer());
                testrecord.setId(t.getId());
                RuleExecutor ruleExecutor = new RuleExecutor();
                Score score= ruleExecutor.processRules(testrecord);
                scoreRepository.save(score);    
            }

        }

}

0 个答案:

没有答案