gpt4 book ai didi

java - 一起使用@postconstruct 和@Scheduled 注解

转载 作者:行者123 更新时间:2023-11-30 06:50:51 34 4
gpt4 key购买 nike

我是新手,正在使用 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. 其他人不会 Autowiring 此组件。

还有更多的原因,但我到此为止。

关于java - 一起使用@postconstruct 和@Scheduled 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40909160/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com