【问题标题】:initialization and schedule in spring bootspring boot中的初始化和调度
【发布时间】:2020-03-12 01:12:09
【问题描述】:

您好,我阅读了这段代码:


@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 OfflineAttributesComputerofflineAttributesComputer? 我们应该使用 public static OfflineAttributesComputer offlineAttributesComputer 吗?

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

【问题讨论】:

    标签: java spring spring-boot oop design-patterns


    【解决方案1】:
    1. @Singleton 有必要吗?如果我们删除它会发生什么?

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 2017-12-10
      • 2017-03-28
      • 2018-03-22
      • 1970-01-01
      • 2020-12-14
      相关资源
      最近更新 更多