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

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

猜你喜欢

转载自blog.csdn.net/qq_40883132/article/details/81388590
今日推荐