繁体   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