第七章 Spring自定义事件

来源:互联网 发布:unity3d开始界面添加 编辑:程序博客网 时间:2024/05/16 02:55

一、自定义事件,集成ApplicationEvent

package demo2.event;import org.springframework.context.ApplicationEvent;public class DemoEvent extends ApplicationEvent {    private static final long serialVersionUID = 1L;    private String msg;    public DemoEvent(Object source, String msg) {        super(source);        this.msg = msg;    }    public String getMsg() {        return msg;    }}

二、定义事件监听器,实现ApplicationListener

package demo2.event;import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;@Componentpublic class DemoEventListener implements ApplicationListener<DemoEvent> {    @Override    public void onApplicationEvent(DemoEvent event) {        String msg = event.getMsg();        System.out.println("接收到DemoEvent消息:" + msg);    }}

三、使用容器发布事件

package demo2;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import demo2.config.DIConfig;import demo2.event.DemoEvent;import demo2.service.DemoService;public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext();        cxt.getEnvironment().setActiveProfiles("dev");        cxt.register(DIConfig.class);        cxt.refresh();        DemoService ds = cxt.getBean(DemoService.class);        //ds.sayDemo("Spring");        cxt.publishEvent(new DemoEvent(cxt, "context init"));        //ds.publisher("context init finish");        cxt.close();    }}

运行结果

接收到DemoEvent消息:context init
0 0
原创粉丝点击