標籤:com tms rri static div pac set [] auto
spring的事件,為Bean與Bean之間通訊提供了支援,當一個Bean處理完成之後,希望另一個Bean知道後做相應的事情,這時我們就讓另外一個Bean監聽當前Bean所發送的事件。
spring的事件應該遵循:
1.自訂事件,整合:ApplicationEvent
2.自訂事件監聽,實現ApplicationListener
3.使用容器發布事件
//自訂事件
package ch2.event;import org.springframework.context.ApplicationEvent;//自訂事件public class DemoEvent extends ApplicationEvent {private static final long serialVerisionUID = 1L;private String msg;public DemoEvent(Object source, String msg) {super(source);// TODO Auto-generated constructor stubthis.msg = msg;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}
//事件監聽器
package ch2.event;import org.springframework.context.ApplicationEvent;import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;//事件監聽器//@Component把普通pojo執行個體化到spring容器中,相當於設定檔中的<bean id="" class=""/>//@service注入:當前類是spring管理的一個bean@Componentpublic class DemoListener implements ApplicationListener<DemoEvent> {@Overridepublic void onApplicationEvent(DemoEvent event) {// TODO Auto-generated method stub//接受訊息String msg = event.getMsg();//列印訊息System.out.println("我(bean-DemoListener)接收到了bean-DemoPublisher發布的訊息:"+msg);}}
//事件發送
package ch2.event;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;//事件發送//把普通pojo執行個體化到spring容器中當成一個Bean@Componentpublic class DemoPublisher {//將ApplicationContext類的實體Bean注入到DemoPublisher中,讓DemoPublisher擁有ApplicationContext的功能//使用applicationContext來發布事件@AutowiredApplicationContext applicationContext;public void publish(String msg){//使用applicationContext的event來發布訊息applicationContext.publishEvent(new DemoEvent(this, msg));}}
配置類
package ch2.event;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.ComponentScan;//聲明本類是一個配置類@Configuration//匯入ch2.event包下的所有@Service,@Component,@Repository,@Controller註冊為Bean@ComponentScan("ch2.event")public class EventConfig {}
運行:
package ch2.event;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args){AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);demoPublisher.publish("hello application event");context.close();}}
結果:
我(bean-DemoListener)接收到了bean-DemoPublisher發布的訊息:hello application event
spring boot: 一般注入說明(五) @Component, application event事件為Bean與Bean之間通訊提供了支援