Spring入门总结(五)自定义事件

本文介绍如何在Spring框架中自定义事件发布与处理流程,包括创建CustomEvent类、事件发布类EventClassPublisher及事件处理类CustomEventHandler。同时展示了如何通过XML配置文件及注解方式配置这些组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.自定义一个CustomEvent类继承ApplicationEvent。

生成构造器,重写toString方法;

package com.tutorialspoint;

import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent {

	public CustomEvent(Object source) {
		super(source);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return  "My Custom Event";
	}
}

2.自定义一个事件发布类,EventClassPublisher ,实现ApplicationEventPublisherAware接口。

package com.tutorialspoint;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class EventClassPublisher  implements ApplicationEventPublisherAware{
	private ApplicationEventPublisher publisher; 
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
		// TODO Auto-generated method stub
		this.publisher = publisher;
	}
	public void publish() {
		CustomEvent customEvent = new CustomEvent(this); 
		publisher.publishEvent(customEvent);
	}

}
 

3.事件处理,自定义一个CustomEventHandler

package com.tutorialspoint;

import org.springframework.context.ApplicationListener;

public class CustomEventHandler implements ApplicationListener<CustomEvent> {

	@Override
	public void onApplicationEvent(CustomEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println(arg0.toString());
	}

}

 xml:

 <bean id="customEventHandler" 
      class="com.tutorialspoint.CustomEventHandler"/>

   <bean id="customEventPublisher" 
      class="com.tutorialspoint.CustomEventPublisher"/>

注意:之所以是要两个bean是因为,事件发布依赖事件处理。

当然也可以使用注解的方式。

自定义一个配置类

package com.tutorialspoint;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.sun.org.apache.bcel.internal.generic.ReturnaddressType;

@Configuration
public class EventclassConfig {
	@Bean
	public EventClassPublisher publish() {
		return new EventClassPublisher();
	}
	@Bean
	public CustomEventHandler handler() {
		return new CustomEventHandler();
	}
}

主函数变成如下:

public static void main(String[] args) {
		ConfigurableApplicationContext context =
		new AnnotationConfigApplicationContext(EventclassConfig.class);
		EventClassPublisher publisher =(EventClassPublisher)context.getBean(EventClassPublisher.class); 
		publisher.publish();
	   }

 

注意:这里配置的bean获取有两种方式:

一个是xxx.class

一个是“方法名"

如:上面的publish和handle

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

江湖无为

感谢你们的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值