自定义事件继承ApplicationEvent
public class MyEvent extends ApplicationEvent { private String message; public MyEvent(Object source) { super(source); } public MyEvent(Object source, String message) { super(source); this.message = message; } public void print() { System.out.println("my message is :"+message); } }
自定义监听器实现ApplicationListener
@Component("myListener")//注入监听器 public class MyEventListener implements ApplicationListener { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof MyEvent) { ((MyEvent)event).print(); } } }
测试:
public class Test { public static void main(String[] args) { ApplicationContext bf = new ClassPathXmlApplicationContext("spring2.xml"); MyEvent event = new MyEvent("hello", "this is my message"); bf.publishEvent(event); //System.out.println(u2); } }
输出:my message is :this is my message