本文共 2226 字,大约阅读时间需要 7 分钟。
Spring 4.1的写法请参考
请对比
使用一个@EventListener
取代了实现ApplicationListener
接口,使耦合度降低;
4.0.0 com.wisely spring4-2 0.0.1-SNAPSHOT jar spring4-2-3 http://maven.apache.org UTF-8 org.springframework spring-context 4.2.3.RC1 spring-milestones Spring Milestones http://repo.spring.io/milestone false
package com.wisely.spring4_2.3.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; } public void setMsg(String msg) { this.msg = msg; }}
编写监听类
package com.wisely.spring4_2.3.event;import org.springframework.context.event.EventListener;import org.springframework.stereotype.Component;@Componentpublic class DemoListener { @EventListener //注意此处 public void handleDemoEvent(DemoEvent event){ System.out.println("我监听到了pulisher发布的message为:"+event.getMsg()); }}
测试
package com.wisely.spring4_2.3.event;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.stereotype.Component;@Componentpublic class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.wisely.spring4_2.event"); Main main =context.getBean(Main.class); main.pulish(context); context.close(); } public void pulish(AnnotationConfigApplicationContext context){ context.publishEvent(new DemoEvent(this, "22")); }}
输出结果 我监听到了pulisher发布的message为:22
转载地址:http://qjcpi.baihongyu.com/