gpt4 book ai didi

java - Spring Boot中的初始化和调度

转载 作者:行者123 更新时间:2023-12-02 08:53:16 26 4
gpt4 key购买 nike

嗨,我读了这段代码:


@Configuration
@Singleton
public class myConfig {
private static final org.apache.logging.log4j.Logger LOGGER = LogManager.getLogger(myConfig.class);


public OfflineAttributesComputer offlineAttributesComputer;

@PostConstruct
public void init() {
offlineAttributesComputer = getOfflineAttributesComputer();
}

public OfflineAttributesComputer getOfflineAttributesComputer(){
OfflineAttributesComputer computer = new OfflineAttributesComputer();
LOGGER.info("Successfully initialized offline computer.");
return computer;
}

@Scheduled(fixedRate = 600000)
public void updateOfflineAttributesComputer(){
try {
offlineAttributesComputer = getOfflineAttributesComputer();
LOGGER.info("Successfully updated offline computer.");
} catch (Exception e) {
throw new EventBrokerException("Failed.", e);
}
}
}

基本功能就像初始化一个单例对象,初始化后,为 offlineAttributesComputer 分配一些值。然后每十分钟更新一次变量。

有几点我不明白:

  1. @Singleton有必要吗?如果我们删除它会发生什么?

  2. 在类中定义了public OfflineAttributesComputer offlineAttributesComputer?我们应该使用 public static OfflineAttributesComputer OfflineAttributesComputer 吗?

  3. 为什么我们需要@PostConstruct,我们可以以正常方式初始化并安排更新吗?

最佳答案

  1. is @Singleton necessary? what happen if we remove it?

嗯,这不是 Spring 注释。我认为不需要它,因为 Singleton 是默认范围,请参见此处:Scope of @Configuration Class in spring

  1. in the class defined the public OfflineAttributesComputer offlineAttributesComputer? should we use public static OfflineAttributesComputer offlineAttributesComputer?

不,不需要static。您正在将纯 Java 的单例设计模式实现与 Spring 方式混合在一起。

  1. why do we need @PostConstruct, can we just initialize in a normal way and schedule the update?

从您发布的代码来看,它是不需要的,我的意思是它也可以在 getter 中完成,但是 OfflineAttributesComputer 不是一个 bean。可能作者不希望其他人能够在其他类中 Autowiring ...

关于java - Spring Boot中的初始化和调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60646393/

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