下面展示一些 内联代码片
。
实体类需要继承ApplicationEvent
public class UserEvent extends ApplicationEvent{
//操作人
String name;
//时间
String time;
//user实体
User user;
public UserEvent(User user,String name, String time) {
super(user);
this.name= name;
this.time= time;
}
需要有getset方法
在使用的地方加上
@Service
public class UserService {
@Resource
private ApplicationEventPublisher applicationEventPublisher;
public void register(String name) {
//需要监听的地方里面进行调用
//写入一些实体类需要的参数
User user = new User();
user.setName("张三");
user.setAge("18");
user.setSex("男");
applicationEventPublisher.publishEvent(new UserEvent(user,"张三","20200111"));
}
}
注: 再Spring中,服务必须交给 Spring 容器托管。ApplicationEventPublisherAware 是由 Spring 提供的用于为 Service 注入 ApplicationEventPublisher 事件发布器的接口,使用这个接口,我们自己的 Service 就拥有了发布事件的能力。触发后,不再是显示调用其他的业务 Service,而是发布一个事件。
附上ApplicationEventPublisher 源码
ApplicationEventPublisher是ApplicationContext的父接口之一。这接口的作用是:Interface that encapsulates event publication functionality.
功能就是发布事件,也就是把某个事件告诉的所有与这个事件相关的监听器。
这个方法会通知的所有与事件相匹配的监听器。这些监听可能是spring框架的监听器,也有可能是特定的监听器
这个接口只有两个方法(这两个是重载方法)
@FunctionalInterface
public interface ApplicationEventPublisher {
/**
* Notify all <strong>matching</strong> listeners registered with this
* application of an application event. Events may be framework events
* (such as RequestHandledEvent) or application-specific events.
* @param event the event to publish
* @see org.springframework.web.context.support.RequestHandledEvent
*/
default void publishEvent(ApplicationEvent event) {
publishEvent((Object) event);
}
/**
* Notify all <strong>matching</strong> listeners registered with this
* application of an event.
* <p>If the specified {@code event} is not an {@link ApplicationEvent},
* it is wrapped in a {@link PayloadApplicationEvent}.
* @param event the event to publish
* @since 4.2
* @see PayloadApplicationEvent
*/
void publishEvent(Object event);
}
写一个类进行会重写ApplicationListener的方法
在onApplicationEvent里面写入下面系列的操作
@Component
class UserApplicationEvent implements ApplicationListener<UserEvent> {
@Resource
private UserService userService;
//假设监听后保存这个user用户
@Override
public void onApplicationEvent(UserEvent userEvent) {
User user = userEvent.getUser();
userService.save(user);
}
}