简体   繁体   中英

Spring SmartLifeCycle does not seem to work with post construct

I am using Spring SmartLifeCycle to specify bean order as follows:

public class MyBean implements SmartLifecycle {
    @PostConstruct
    public void init() {
        //Do stuff
    }

private boolean isRunning = false;

    @Override
    public boolean isAutoStartup() {
        LOGGER.warn("************** is autostartp");
        return true;
    }

    @Override
    public void stop(final Runnable callback) {
        stop();
        callback.run();
    }

    @Override
    public void start() {
        LOGGER.warn("************** start ");
        isRunning = true;
    }

    @Override
    public void stop() {
        LOGGER.warn("************** stop");
        isRunning = false;
    }

    @Override
    public boolean isRunning() {
        LOGGER.warn("************** is running" + isRunning);
        return isRunning;
    }

    @Override
    public int getPhase() {
        LOGGER.warn("************** phase " + (Integer.MIN_VALUE));
        return Integer.MIN_VALUE;
    }
}

The order does not seem to be running correctly. All the beans seem to be constructed before the phase is even considered, which is causing by application to fail startup.

How can I fix this and correctly specify the order? Am I using this incorrectly?

Looks like you are missing the getPhase() method. This is used to control the order that the beans are instantiated. During shutdown, the order is reversed.

Any beans that don't have an explicit phase are either assigned phase 0 (most common) or given a phase by Spring (if it's something managed by Spring like a JMS listener).

Unless you explicitly assign a phase, Spring will make a "best guess" which may not yield the desired result.

@Override
public int getPhase() {
    return 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM