首页 > 解决方案 > spring boot中的初始化和调度

问题描述

嗨,我读了这段代码:


@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是必要的吗?如果我们删除它会发生什么?</p>

  2. 在类中定义了公共的 OfflineAttributesComputer offlineAttributesComputer?我们应该使用公共静态 OfflineAttributesComputerofflineAttributesComputer 吗?

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

标签: javaspringspring-bootoopdesign-patterns

解决方案


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

好吧,这不是 Spring 注释。我相信它是不需要的,因为 Singleton 是默认范围,请参见此处:春季 @Configuration 类的范围

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

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

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

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


推荐阅读