Lifecycle Interface in Spring

Lifecycle Interface Overview

Spring containers possess inherent lifecycle states. To synchronize managed beans (e.g., database connections) with container events, implement the Lifecycle interface:

public interface Lifecycle {
    void start();
    void stop();
    boolean isRunning();
}
  • start(): Initiates object lifecycle
  • stop(): Terminates object lifecycle
  • isRunning(): Checks active lifecycle state

LifecycleProcessor Extension

Enhanced interface for lifecycle management:

public interface LifecycleProcessor extends Lifecycle {
    void onRefresh();
    void onClose();
}

Container Lifecycle Implementation

AbstractApplicationContext delegates to LifecycleProcessor:

public void start() {
    getLifecycleProcessor().start();
    publishEvent(new ContextStartedEvent(this));
}

public void stop() {
    getLifecycleProcessor().stop();
    publishEvent(new ContextStoppedEvent(this));
}

During initialization:

protected void finishRefresh() {
    initLifecycleProcessor();
    getLifecycleProcessor().onRefresh();
    publishEvent(new ContextRefreshedEvent(this));
}

Processor initialization logic:

protected void initLifecycleProcessor() {
    if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
        this.lifecycleProcessor = beanFactory.getBean(...);
    } else {
        DefaultLifecycleProcessor processor = new DefaultLifecycleProcessor();
        processor.setBeanFactory(beanFactory);
        this.lifecycleProcessor = processor;
    }
}

Lifecycle Execution Process

Default processor handles bean lifecycles:

private void startBeans(boolean autoStart) {
    Map<String, Lifecycle> beans = getLifecycleBeans();
    Map<Integer, LifecycleGroup> groups = new HashMap<>();
    
    beans.forEach((name, bean) -> {
        if (!autoStart || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
            int phase = getPhase(bean);
            groups.computeIfAbsent(phase, p -> new LifecycleGroup(...))
                  .add(name, bean);
        }
    });
    
    groups.keySet().stream()
          .sorted()
          .forEach(phase -> groups.get(phase).start());
}

SmartLifecycle Extension

Adds priority control and auto-start configuration:

public interface SmartLifecycle extends Lifecycle, Phased {
    int DEFAULT_PHASE = Integer.MAX_VALUE;
    
    default boolean isAutoStartup() { return true; }
    
    default void stop(Runnable callback) {
        stop();
        callback.run();
    }
    
    default int getPhase() { return DEFAULT_PHASE; }
}

Behavior demonstration:

public class BeanTuDong implements SmartLifecycle {
    private boolean active;
    
    public boolean isAutoStartup() { return true; }
    
    public void start() {
        System.out.println("Bean tự động khởi động");
        active = true;
    }
    // stop() and isRunning() implementations
}

public class BeanThuCong implements SmartLifecycle {
    public boolean isAutoStartup() { return false; }
    // Other implementations
}

Test output:

Khởi tạo container
Bean tự động khởi động
Kích hoạt container
Bean thủ công khởi động
Đóng container
Bean tự động dừng
Bean thủ công dừng

Thẻ: Lifecycle SmartLifecycle SpringFramework LifecycleProcessor

Đăng vào ngày 6 tháng 6 lúc 01:43