Springフレームワークによって開発されたSmartLifecycleインターフェース



Smartlifecycle Interface Developed Spring Framework



Springで開発する場合、各Beanのロードと初期化を含め、すべてのBeanが統合管理のためにSpringコンテナーに渡されることは誰もが知っています。 SpringがすべてのBeanをロードして初期化した後、いくつかのタスクまたはビジネスロジックを実行する必要がある場合があります。次に、SmartLifecycleインターフェースが役立ちます。ソースコードを見てみましょう

public interface SmartLifecycle extends Lifecycle, Phased { boolean isAutoStartup() void stop(Runnable callback) }

その親



public interface Lifecycle { void start() void stop() boolean isRunning() }

SmartLifecycleはインターフェースです。 Springコンテナは、すべてのBeanをロードして初期化を完了すると、インターフェイスを実装するクラスの対応するメソッド(start()メソッド)をコールバックします。次に、Eurekaでのこのインターフェースの実装を見てみましょう。

@Configuration @CommonsLog public class EurekaServerInitializerConfiguration implements ServletContextAware, SmartLifecycle, Ordered { @Override public void start() { new Thread(new Runnable() { @Override public void run() { try { //TODO: is this class even needed now? eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext) log.info('Started Eureka Server') publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig())) EurekaServerInitializerConfiguration.this.running = true publish(new EurekaServerStartedEvent(getEurekaServerConfig())) } catch (Exception ex) { // Help! log.error('Could not initialize Eureka servlet context', ex) } } }).start() } } ここでの使用法は、すべてのSpringBeanがロードされた後にEurekaサーバーを起動することです。サービスの登録と発見を実現します。