春のイベント(1) - 内蔵のイベント


チュートリアルの春シリーズ


春のイベントがあるApplicationEventの実現により、クラスのサブクラスApplicationEventPublisherAware実装するクラスの送信インタフェースApplicationListenerクラスのモニタインタフェースを。

ApplicationContextのイベント

春はすでに組み込みのイベントのセットを定義しているApplicationContextコンテナの問題。

例えば、ContextStartedEventApplicationContextスタートを送信し、送信を停止。ContextStoppedEventApplicationContext

達成ApplicationListenerクラスはイベントをリッスンすることができます。

春のイベントは、(シングルスレッド)同期されているブロックされます。

ApplicationContextのモニター・イベント

リッスンするApplicationContextイベント、リスナクラスが実装すべきApplicationListenerインタフェースをしてオーバーライドするonApplicationEvent()方法を。

ContextStartEventHandler.java

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

public class ContextStartEventHandler implements ApplicationListener<ContextStartedEvent>{

    @Override
    public void onApplicationEvent(ContextStartedEvent event) {
        System.out.println("ApplicationContext 启动... ");
    }
}

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
  public static void main(String[] args) {
    // ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    // fire the start event.
    // ((ConfigurableApplicationContext) context).start();
    
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    // fire the start event.
    context.start();
    
    // ...
    
  }
}

XML設定ファイルでは、クラスがビーンをロードする春のコンテナは、ビーンとして宣言し、そのイベントを送信しています。

<bean id="contextStartEventHandler" class="ContextStartEventHandler"></bean>

おすすめ

転載: www.cnblogs.com/jinbuqi/p/10987724.html