Spring学习六:自定义Event事件

Spring 中的自定义事件

编写和发布自己的自定义事件有许多步骤。按照在这一章给出的说明来编写,发布和处理自定义 Spring 事件。

步骤描述
1 创建一个名称为 SpringExample 的项目,并且在创建项目的 src 文件夹中创建一个包 com.tutorialspoint。
2 使用 Add External JARs 选项,添加所需的 Spring 库,解释见 Spring Hello World Example 章节。
3 通过扩展 ApplicationEvent,创建一个事件类 CustomEvent。这个类必须定义一个默认的构造函数,它应该从 ApplicationEvent 类中继承的构造函数。
4 一旦定义事件类,你可以从任何类中发布它,假定 EventClassPublisher 实现了 ApplicationEventPublisherAware。你还需要在 XML 配置文件中声明这个类作为一个 bean,之所以容器可以识别 bean 作为事件发布者,是因为它实现了 ApplicationEventPublisherAware 接口。
5 发布的事件可以在一个类中被处理,假定 EventClassHandler 实现了 ApplicationListener 接口,而且实现了自定义事件的 onApplicationEvent 方法。
6 在 src 文件夹中创建 bean 的配置文件 Beans.xml 和 MainApp 类,它可以作为一个 Spring 应用程序来运行。
7 最后一步是创建的所有 Java 文件和 Bean 配置文件的内容,并运行应用程序,解释如下所示。

 

自定义一个EventTest

package spring.event;

import org.springframework.context.ApplicationEvent;

public class EventTest extends ApplicationEvent {
    private static final long serialVersionUID = 1L;
    private String message;
    public EventTest(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

定义EventPbulish

package spring.event;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class EventPbulish {
    @Autowired
    ApplicationContext context;
    public void publish(String message) {
        context.publishEvent(new EventTest(this, message));
    }
}

定义ListenerTest

package spring.event;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ListenerTest implements ApplicationListener<EventTest> {
    public void onApplicationEvent(EventTest event) {
        System.out.println("test1:" + event.getMessage());
    }
}

baen注入容器配置类

package spring.event;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("spring.event")
public class ConfigTest {

}

测试类

package spring.event;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ConfigTest.class);
        EventPbulish eventPbulish = context.getBean(EventPbulish.class);
        eventPbulish.publish("zhangsan");
        context.close();
    }
}

 

posted @ 2020-09-01 23:57  纵码万水千山  阅读(421)  评论(0编辑  收藏  举报