2016-12-01 263 views
1

我是新學習者,並且使用Spring註解進行配置我可以使用@PostConstruct和@Scheduled(fixedRate = 60L * 1000L) ,它們的方法與下面給出的方法相同嗎?如果是的話,班級的註釋應該是什麼?@postconstruct和@Scheduled註解在一起

@Component 
public class Cache { 

    @PostConstruct 
    @Scheduled(fixedRate = 60L * 1000L) 
    public void refreshCache() { 
    ... 
    } 

} 
+0

如果你使用的是spring引導,那麼'@ EnableScheduling'註釋應該和'@SpringBootApplication'一起指定,並且確保你的任務可以被你的spring引導應用程序掃描,這實際上是一個可以被註釋的公共bean '@ Component'就像你做的一樣。 –

+0

我沒有使用Spring啓動 – Shailesh

+0

如果沒有,您可以看到類「EnableScheduling」的javadoc。 <任務:註解驅動調度= 「的TaskScheduler」/> <任務:調度器ID = 「的TaskScheduler」 池大小= 「42」/> <任務:調度任務調度= 「的TaskScheduler」>

回答

3

是的,你在課堂上的註釋是正確的。但你最好使用:

@Scheduled(fixedRate = 60L * 1000L, initialDelay=0) 
public void refreshCache() { 

沒有@PostConstruct因爲:

  1. 只有在類中的一個方法可以用@PostConstruct註解。
  2. 您不能使用@PostConstruct從方法中拋出檢查的異常。
  3. 其他人不會自動裝配此組件。

還有更多的原因,但我停在這裏。

+0

我試過@Scheduled(fixedRate = 60L * 1000L,initialDelay = 0),但它沒有調用方法..! – Shailesh

+0

@Shailesh然後,在課外有什麼不對。請發佈你的'web.xml'。 –

+0

其實我沒有使用任何XML進行配置,它純粹是基於註釋的配置 – Shailesh

0

如果你不使用任何xml,這個例子應該是你想要的,這實際上是一個spring引導應用程序。 https://github.com/soiff-spring/spring-boot-example


我的完整的例子是在這裏:https://github.com/soiff-spring/spring-mvc-example

請注意以下文件和類:

  1. hello-servlet.xml
  2. HelloScheduler

Packaing這個項目,並把它在你的tomcat容器中並啓動你的tomcat,你會看到如下日誌:

20:06:53.003 [pool-1-thread-1] INFO xyz.cloorc.example.springmvc.HelloScheduler - 1480594013001 : hello world ... 
20:06:54.001 [pool-1-thread-1] INFO xyz.cloorc.example.springmvc.HelloScheduler - 1480594014001 : hello world ... 
20:06:55.001 [pool-1-thread-1] INFO xyz.cloorc.example.springmvc.HelloScheduler - 1480594015001 : hello world ... 
20:06:56.002 [pool-1-thread-1] INFO xyz.cloorc.example.springmvc.HelloScheduler - 1480594016002 : hello world ... 
20:06:57.000 [pool-1-thread-1] INFO xyz.cloorc.example.springmvc.HelloScheduler - 1480594017000 : hello world ... 
20:06:58.002 [pool-1-thread-1] INFO xyz.cloorc.example.springmvc.HelloScheduler - 1480594018002 : hello world ... 

享受你自己。

+0

正如我的研究,只有'@ Scheduled'將在註解'@ PostConstruct'一起指定時纔會生效。 –

相關問題