2011-08-01 34 views
6

任何人都可以解釋如何使用@Scheduled註釋實現任務的基本配置而無需任何XML配置?我可以找到的所有示例至少使用最少的XML配置。例如:註解驅動任務的Spring @Configuration(非xml配置)

http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/

它使用一個典型:

<context:component-scan base-package="org/springframework/samples/task/basic/annotation"/> 
    <task:annotation-driven/> 

所以我只是用@Configuration註釋與一羣@Bean註解。它們都在啓動時實例化,但帶有@Scheduled的那個不運行。過去,在使用XML配置時,我已經成功地使用了該註釋,但從未僅使用註釋。

回答

4

<task:annotation-driven />註釋最終聲明瞭一個ScheduledAnnotationBeanPostProcessor來讀取代碼中的@Scheduled註釋。看到這裏:http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.html

這需要照顧<task:annotation-driven />一行。要獲取組件掃描,您需要使用AnnotationConfigApplicationContext。不知道是否/如何與Web容器一起工作。

+0

請注意,即使我的鏈接是3.1文檔,ScheduledAnnotationBeanPostProcessor也存在3.0。 – Kevin

+0

是聲明\ @Configuration類中的ScheduledAnnotationBeanPostProcessor,因爲\ @Bean似乎有效 - 意味着它完成了任務:註釋驅動的任務。 – david

3

在Spring 3.0中,您仍然需要這麼一點XML。然而,Spring 3.1(仍在測試版)引入了額外的註釋選項來縮小差距,消除了對XML配置的任何需求。

有關如何完成,請參閱this blog entry。儘管在生產代碼中使用Spring的Beta版本之前要非常小心 - 它們確實不穩定。

15

剛上添加@EnableScheduling WebMvcConfig類

@Configuration 
@EnableWebMvc 
@EnableAsync 
@EnableScheduling 
public class WebMvcConfig extends WebMvcConfigurerAdapter { 
    /** Annotations config Stuff ... **/ 
} 
+1

是的,問題出在Spring 3.1可用之前。 – david

0

答案至今都爲早期版本的春天有幫助的。 這裏是一個更適合春4位:

假設您有註解的組件主要應用程序級的掃描是這樣的:

@ComponentScan({"com.my.class"}) 

這包裏面,你有一份工作類看起來是這樣的:

@Configuration 
@EnableScheduling 
public class MyJobClass { 
@Scheduled (cron = "* * * * * *") 
public void runJob() throws DocumentException { 
    thingsToDoOnSchedule(); 
    } 
} 

需要注意的是,你與@Scheduled註釋方法必須返回void,並且您的cron表達式需要有6個字符(這裏顯示的示例運行每秒,這使得測試你的工作更容易)。

您還需要@Configuration和@EnableScheduling的類級別註釋才能完成此工作。要麼他們自己似乎被忽略。

如需進一步閱讀,請點擊這裏Spring 4 Enable Scheduling Reference Doc

相關問題