编写测试事件
package com.itdfq.springlistener.event;
import org.springframework.context.ApplicationEvent;
public class TestEvent extends ApplicationEvent {
private String name;
public TestEvent(Integer source, String name) {
super(source);
this.name = name;
}
public String getName() {
return name;
}
}
编写对应的监听器
package com.itdfq.springlistener.event;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class TestEventHandler implements ApplicationListener<TestEvent> {
@Override
public void onApplicationEvent(TestEvent testEvent) {
System.out.println("处理器执行了");
System.out.println(testEvent);
System.out.println(testEvent.getName());
System.out.println(testEvent.getSource());
}
}
测试
package com.itdfq.springlistener;
import com.itdfq.springlistener.event.TestEvent;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationEventPublisher;
import javax.annotation.Resource;
@SpringBootTest
class SpringListenerApplicationTests {
@Resource
private ApplicationEventPublisher eventPublisher;
@Test
void contextLoads() {
eventPublisher.publishEvent(new TestEvent(123,"李白"));
}
}
结果