簡體   English   中英

一起使用@postconstruct和@Scheduled批注

[英]using @postconstruct and @Scheduled annotation together

我是新手,並且使用spring批注進行配置是否可以按以下相同方法使用@PostConstruct和@Scheduled(fixedRate = 60L * 1000L)? 如果是,應該為類添加什么注釋?

@Component
public class Cache {

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

}

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

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

沒有@PostConstruct原因是:

  1. 該類中只有一個方法可以使用@PostConstruct進行注釋。
  2. 您不能使用@PostConstruct從方法中引發檢查的異常。
  3. 其他人將不會自動連接該組件。

還有更多原因,但我在這里止步。

如果您不使用任何xml,則此示例應該是您想要的,它實際上是一個Spring Boot應用程序。 https://github.com/soiff-spring/spring-boot-example


我的完整示例在這里: https : //github.com/soiff-spring/spring-mvc-example

請注意以下文件和類:

  1. hello-servlet.xml
  2. HelloScheduler

包裝此項目並將其放入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 ...

玩的開心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM