简体   繁体   中英

Spring SmartLifeCycle sequential behavior?

I have an application that is broken down into several modules. I created a class whose job is to start them in the right order and give each module enough time to start. I have messed with SmartLifeCycle quite a bit in the past but i would like to know more about how it would behave if i was to use it for my modules instead of needing a separate class that handles each modules's startups and shutdowns.

For example, module A takes quite a bit of time to start as it needs to initialize several TCP connections to other systems. Module B is dependent on module A being fully initialized as it sends various messages to these clients. If i make each module implement SmartLifeCycle and give them the correct phase so they start in the right order, can i assume that Spring will fully initialize one before moving to the next? Do we have any control over this behavior?

IMO it's better to use an event-driven way to control your "modules". If I understand you correctly in each modules you have some services which should do some job depending on each other. So in this case, you can publish the necessary events and implement some listeners that react to these events and call the correspond methods of those servers, then publish other events that trigger the next part of listeners, etc.

For example:

@Component
public class FirstHandler {
    @Autoware private FirstService service;

    @EventListener(ApplicationReadyEvent.class) // start when App is ready
    public FirstWorkCompleted onAppReady() {
        service.doWork();
        return new FirstWorkCompleted(); // send FirstWorkCompleted event
    }
}
@Component
public class SecondHandler {
    @Autoware private SecondService service;

    @EventListener(FirstWorkCompleted.class) // start when First work is completed
    public SecondWorkCompleted onFirstWorkCompleted() {
        service.doWork();
        return new SecondWorkCompleted(); // send SecondWorkCompleted event
    }
}

You can also send events with ApplicationEventPublisher - just inject it in your component.

@EventListener methods can work asynchronously - just add @Async annotation to such methods (don't forget to apply @EnableAsync annotation to your config or application class as well).

@EventListener methods can be ordered - just add @Order annotation to them with desired order.

More info about application event:

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