Spring---ApplicationContextのイベントメカニズム
2792 ワード
:ApplicationContext。publishEvent() : 。
:ApplicationEvent , , ApplicationContext 。
:ApplicationListener , Bean 。onApplicationEvent(ApplicationEvent event): ,
コンテナイベントクラスはApplicationEventクラスを継承し、コンテナイベントのリスナークラスはApplicationListenerインタフェースを実装する必要があります.
次に例を示します
1.まずEmailEventクラスを定義し、ApplicationEventクラスを継承する
public class EmailEvent extends ApplicationEvent {
private String address;
private String text;
public EmailEvent(Object source) {
super(source);
}
public EmailEvent(Object source, String address, String text) {
super(source);
this.address = address;
this.text = text;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
2,EmailNotifierクラスを定義し、ApplicationListenerインタフェースを実装し、onApplicationEvent()メソッドを複写する
public class EmailNotifier implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent instanceof EmailEvent){
EmailEvent emailEvent = (EmailEvent) applicationEvent;
System.out.println(" : " + emailEvent.getAddress());
System.out.println(" : " + emailEvent.getText());
}else {
System.out.println(" : " + applicationEvent);
}
}
}
3.リスナーをコンテナに配置する
<bean class="org.spring.listener.EmailNotifier"/>
4.メインプログラムmainの作成
public class SpringTest {
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");
// EmailEvent ele = new EmailEvent("hello","[email protected]","this is a test");
// ctx.publishEvent(ele);
}
}
プログラムはこれで終わり、実行結果は次のとおりです.
: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@b81eda8: startup date [Thu Dec 04 20:20:52 CST 2014]; root of context hierarchy]
mainのコメントをキャンセルすると、publishEvent()を使用してイベントがトリガーされます.実行結果は次のとおりです.
: org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@b81eda8: startup date [Thu Dec 04 20:24:03 CST 2014]; root of context hierarchy]
: [email protected]
: this is a test