关于Spring事件机制ApplicationEventPublisher的使用

下面展示一些 内联代码片

实体类需要继承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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值