扫码一下
查看教程更方便
本篇我们介绍spring 中的自定义事件,编写和发布自己的自定义事件需要执行多个步骤。 按照本章给出的说明编写、发布和处理自定义 spring 事件。
这是 customevent.java 文件的内容
customevent.java
package com.jiyik; import org.springframework.context.applicationevent; public class customevent extends applicationevent{ public customevent(object source) { super(source); } public string tostring(){ return "my custom event"; } }
以下是 customeventpublisher.java 文件的内容
customeventpublisher.java
package com.jiyik; import org.springframework.context.applicationeventpublisher; import org.springframework.context.applicationeventpublisheraware; public class customeventpublisher implements applicationeventpublisheraware { private applicationeventpublisher publisher; public void setapplicationeventpublisher (applicationeventpublisher publisher) { this.publisher = publisher; } public void publish() { customevent ce = new customevent(this); publisher.publishevent(ce); } }
以下是 customeventhandler.java 文件的内容
customeventhandler.java
package com.jiyik; import org.springframework.context.applicationlistener; public class customeventhandler implements applicationlistener
{ public void onapplicationevent(customevent event) { system.out.println(event.tostring()); } }
以下是 mainapp.java 文件的内容
mainapp.java
package com.jiyik; import org.springframework.context.configurableapplicationcontext; import org.springframework.context.support.classpathxmlapplicationcontext; public class mainapp { public static void main(string[] args) { configurableapplicationcontext context = new classpathxmlapplicationcontext("beans.xml"); customeventpublisher cvp = (customeventpublisher) context.getbean("customeventpublisher"); cvp.publish(); cvp.publish(); } }
以下是配置文件beans.xml
beans.xml
完成源代码和 bean 配置文件后,让我们运行应用程序。 如果应用程序一切正常,它将打印以下消息
y custom event
y custom event