mercredi 11 mars 2020

initialization and schedule in spring boot

HI i read this piece of code:


@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 = new OfflineAttributesComputer();
            LOGGER.info("Successfully updated offline computer.");
        } catch (Exception e) {
            throw new EventBrokerException("Failed.", e);
        }
    }
}

The basic function is like initialize a singleton object and after initialization, assign offlineAttributesComputer some value. then every ten minutes update the varible.

There are some points I don't understand:

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

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

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

Aucun commentaire:

Enregistrer un commentaire