spring事件

1、Spring简单事件使用步骤:

1、自定义事件 并继承 ApplicationEvent

2、定义事件的监听器类

3、发布事件

2、代码示例:

  • Demo实体
package com.hh;

@Data
public class Demo {
    private String demoMsg;
}
  • 事件类
package com.hh;

import org.springframework.context.ApplicationEvent;

public class DemoEvent extends ApplicationEvent {
    
    private Demo demo;
    
    public Demo getDemo() {
        return demo;
    }
    
    public DemoEvent(Object source, Demo demo) {
        super(source);
        this.demo=demo;
    }
}
  • 监听器类
package com.hh;

import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class DemoListener {
    
    @EventListener
    @Async
    public void sendMsg(DemoEvent demoEvent){
        Demo demo = demoEvent.getDemo();
        System.out.println("DemoListener接受到了EventPublisher发布的消息: "+demo.getDemoMsg());
        
    }
}
  • 发布类
package com.hh;

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

@Component
public class EventPublisher<T extends ApplicationEvent> {
    
    @Autowired
    private ApplicationContext applicationContext;
    
    public void eventPublish(T event){
        System.out.println("发布event事件: "+event);
        applicationContext.publishEvent(event);
    }
}
  • 测试
package com.hh;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoTest {
    
    @Autowired
    EventPublisher<DemoEvent> eventPublisher;
    
    @Test
    public void eventTest(){
        Demo demo=new Demo();
        demo.setDemoMsg("event测试事件!!");
        DemoEvent demoEvent = new DemoEvent(this,demo);
        eventPublisher.eventPublish(demoEvent);
    }
}