实现Spring的事件监听有两种方法:继承EventListener和@EventListener注解
1.自定义事件
public class MyEvent extends ApplicationEvent {
private String name;
public MyEvent(Object source, String name) {
super(source);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.定义监听器
2.1 注解
@Component
public class MyListener {
@EventListener
public void handleDemoEvent(MyEvent myEvent) {
System.out.println("发短信给:" + myEvent.getName());
}
}
2.2 实现ApplicationListener接口
@Component
public class MyListen2 implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent myEvent) {
System.out.println("发送短信给:" + myEvent.getName());
}
}
3.发布事件
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class PiWebApplicationTests {
@Autowired
private ApplicationContext applicationContext;
@Test
public void testEvent() {
applicationContext.publishEvent(new MyEvent(this, "张三"));
}
}