用户工具

站点工具


spring:event
  • 自定义事件
@SuppressWarnings("serial")
public class CustomizedEvent extends ApplicationEvent {
	/**
	 * @param source CustomizedObj
	 */
	public IntelligenceInfoEvent(Object source) {
		super(source);
	}
}
  • 发布事件
applicationContext.publishEvent(new CostomizedEvent(customizedObj));
  • 监听事件(方法一):使用注解@EventListener
@Component
public class EventListeners {
	@EventListener
	public void handle(CostomizedEvent event) {
		CustomizedObj customizedObj = (CustomizedObj)event.getSource();
	}
}
  • 监听事件(方法二):实现接口ApplicationListener
@Component
public class CostomizedEventListener implements ApplicationListener<CostomizedEvent> {
    @Override
    public void onApplicationEvent(CostomizedEvent event) {
	CustomizedObj customizedObj = (CustomizedObj)event.getSource();
    }
}
  • 监听事件(方法三):实现接口SmartApplicationListener
@Component
public class CostomizedEventListener implements SmartApplicationListener {
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
        return aClass == CostomizedEvent.class;
    }
    public boolean supportsSourceType(Class<?> aClass) {
        return aClass == CostomizedObj.class;
    }
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        CustomizedObj customizedObj = (CustomizedObj)event.getSource();
    }
    //多个监听器时使用order按顺序执行
    public int getOrder() {
        return 0;
    }
}
  • 监听器异步执行
@Configuration
@EnableAsync
public class ListenerAsyncConfiguration implements AsyncConfigurer {
    //配置线程池,异步执行监听器
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}
    //监听器使用注解@Async
    @Async
    public void onApplicationEvent(CostomizedEvent event) {
	CustomizedObj customizedObj = (CustomizedObj)event.getSource();
    }
spring/event.txt · 最后更改: 2018/07/22 17:46 由 admin