Java 同时使用@postconstruct和@Scheduled注释
我是新手,使用spring注释进行配置我可以同时使用@PostConstruct和@Scheduled(fixedRate=60L*1000L)吗 采用与下文相同的方法?如果是,类的注释应该是什么Java 同时使用@postconstruct和@Scheduled注释,java,spring,Java,Spring,我是新手,使用spring注释进行配置我可以同时使用@PostConstruct和@Scheduled(fixedRate=60L*1000L)吗 采用与下文相同的方法?如果是,类的注释应该是什么 @Component public class Cache { @PostConstruct @Scheduled(fixedRate = 60L * 1000L) public void refreshCache() { ... } } 是的,
@Component
public class Cache {
@PostConstruct
@Scheduled(fixedRate = 60L * 1000L)
public void refreshCache() {
...
}
}
是的,您在类中的注释是正确的。但你最好使用:
@Scheduled(fixedRate = 60L * 1000L, initialDelay=0)
public void refreshCache() {
没有@PostConstruct
,因为:
@PostConstruct
注释@PostConstruct
从方法中抛出选中的异常原因还有很多,但我就到此为止。如果您不使用任何xml,这个示例应该是您想要的,它实际上是一个spring引导应用程序
我的完整示例如下: 请注意以下文件和类别:
hello servlet.xml
HelloScheduler
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 ...
尽情享受。如果您使用的是spring boot,则应将
@EnableScheduling
注释与@SpringBootApplication
一起指定,并确保spring boot应用程序可以扫描您的任务,这实际上是一个普通bean,可以像您所做的那样由@Component
进行注释。我没有使用Spring Boot。如果没有,您可以查看关于类启用调度的javadoc。实际上,如果您有正常的applicationContext.xml
,则可以通过
和注释
一起启用注释检测。它应该简单易用。完整名称空间为http://www.springframework.org/schema/context/spring-context.xsd
我没有使用任何xml文件,一切都在注释中。。。!我尝试了@Scheduled(fixedRate=60L*1000L,initialDelay=0),但它没有调用方法@谢里什:那么,课外有些事情不对劲。请发布你的web.xml
。实际上我没有使用任何xml进行配置,它纯粹是基于注释的configuration@Shailesh您没有web.xml
?我没有web.xml我有POM.xml、ehcache.xml和log4j.xml文件。。!我正在通过编码对其进行配置。。!根据我的研究,如果注释@PostConstruct
一起指定,则只有@Scheduled
才会生效。