1. 程式人生 > >Spring Quartz動態設定觸發時間問題

Spring Quartz動態設定觸發時間問題

Spring使用Quartz框架來完成任務排程,有兩種方法:
1. 利用JobDetailBean包裝QuartzJobBean子類(即Job類)的例項。
2. 利用MethodInvokingJobDetailFactoryBean工廠Bean包裝普通的Java物件(即Job類)。

作為開發使用第二種方法是比較方便的,一般在xml檔案中配置好。但是專案有時需要動態改變cronExpression的值,這裡有 QuartzUtils demo 實現程式碼 。過程中遇到了下面的幾個問題。

1.自動注入SchedulerFactoryBean失敗

提示: Failed to convert property value of type [org.quartz.impl.StdScheduler] to required type [org.springframework.scheduling.quartz.SchedulerFactoryBean]

原始碼實現:

@Autowired
private SchedulerFactoryBean schedulerFactoryBean;
@Autowired
private Scheduler scheduler;

2.如何獲取xml中配置的bean

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public
class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } /** * 取得儲存在靜態變數中的ApplicationContext. */
public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 從靜態變數ApplicationContext中取得Bean, 自動轉型為所賦值物件的型別. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); return (T) applicationContext.getBeansOfType(clazz); } /** * 清除applicationContext靜態變數. */ public static void cleanApplicationContext() { applicationContext = null; } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder"); } } } <bean id="myApplication" class="app.util.SpringContextUtil" /> //獲取 Scheduler scheduler = SpringContextUtil.getBean("mySheduler");

3.spring註解 @autowired @resource區別

  1. @Autowired預設是按型別裝配物件的,預設情況下它要求依賴物件必須存在
  2. @Resource預設按名稱裝配,名稱可以通過name屬性指定。當找不到與名稱匹配的bean時,才會按型別裝配