Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法

1,302 阅读1分钟

1.ApplicationEvent发布的对象需要继承的对象

2.ApplicationListener 监听器需要监听的对象

3.首先创建一个ApplicationEvent的实现类

       import org.springframework.context.ApplicationEvent;
        
        public class MailSendEvent extends ApplicationEvent {
        
            public String address;
        
            public String text;
        
        
            public MailSendEvent(Object source) {
                super(source);
            }
        
            public MailSendEvent(Object source, String address, String text) {
                super(source);
                this.address = address;
                this.text = text;
            }
        
            public void print(){
                System.out.println("hello spring event!");
            }
        }

4.给出监听器

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class EmailListener implements ApplicationListener {

    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof MailSendEvent){
            MailSendEvent emailEvent = (MailSendEvent)event;
            emailEvent.print();
            System.out.println("the source is:"+emailEvent.getSource());
            System.out.println("the address is:"+emailEvent.address);
            System.out.println("the email's context is:"+emailEvent.text);
        }
    }
}

5.applicationContext.xml文件配置

  <bean id="emailListener" class="com.EmailListener"></bean>

6.写测试类发布event

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/beans-event.xml");
        MailSendEvent event = new MailSendEvent("hello","123@163.com","this is a email text!");
        context.publishEvent(event);
    }
}

7.测试结果

    hello spring event!
    the source is:hello
    the address is:123@163.com
    the email's context is:this is a email text!