ApplicationEvent和ApplicationListener学习
今日看项目看到了ApplicationEvent抽象类和ApplicationListener接口,之前没有使用过,因此学习了一下。
ApplicationEvent抽象类表示的是某一类事件,比如网站注册的时候,用户注册可以作为一个事件。
public class UserRegistrationEvent extends ApplicationEvent {
private User user;
public UserRegistrationEvent(Object source,User user) {
super(source);
this.user = user;
}
public User getUser(){
return user;
}
}
ApplicationEvent类的使用方法是某个类继承ApplicationEvent,然后重写构造方法。其中的Object source
指的是事件最初发生于哪个对象,或者事件关联的对象,永不为空。
ApplicationListener接口用于对ApplicationEvent事件进行监听。具体使用方法是,类实现ApplicationListener接口,泛型指定要监听的事件类名,重写onApplicationEvent().
@Component
@Slf4j
public class UserEventListener implements ApplicationListener<UserRegistrationEvent> {
@Override
public void onApplicationEvent(UserRegistrationEvent userRegistrationEvent) {
User user = userRegistrationEvent.getUser();
log.info("User对象是{}",user);
}
}
写完这两个类还只是基本工作准备完成,要让这这两个类工作,还需要通过ApplicationContext类的publishEvent(ApplicationEvent applicationEvent)方法,将事件进行发布,然后对应的事件Listener类才会监听到对应的事件,并触发onApplicationEvent()方法。
@Service
public class UserService {
@Autowired
private ApplicationContext applicationContext;
public void registry(User user){
applicationContext.publishEvent(new UserRegistrationEvent(this,user));
}
}
方法启动
2021-11-10 22:34:08.575 INFO 11376 --- [ main] c.e.demo.listener.UserEventListener : User对象是User(name=张三, age=23, address=北京)
运行程序,可以看到,当我调用UserService的registry(User user)方法,applicationContext就会将UserRegistrationEvent事件发布,随后UserEventListener 监听器就监听到了UserRegistrationEvent事件,并自动运行了onApplicationEvent()方法。