Spring中事件监听器
实现ApplicationListener接口
@Configuration public class A48 { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A48.class); context.getBean(MyService.class).doBusiness(); context.close(); } // 定义任务 static class MyEvent extends ApplicationEvent{ public MyEvent(Object source) { super(source); } } @Component @Slf4j static class MyService{ @Resource private ApplicationEventPublisher publisher; public void doBusiness(){ log.info("主线业务"); publisher.publishEvent(new MyEvent("myservice发送的事件")); } } @Component @Slf4j static class SmsApplicationListener implements ApplicationListener{ @Override public void onApplicationEvent(MyEvent event) { log.info("支线任务"); } } }
@EventListener注解
@Component @Slf4j static class SmsApplicationListener{ @EventListener public void listener(MyEvent event){ log.info("发送短信...."); } }
@EventListener结合线程池异步
@Component @Slf4j static class SmsApplicationListener{ @EventListener public void listener(MyEvent event){ log.info("发送短信...."); } } // 线程池异步发送事件 @Bean public ThreadPoolTaskExecutor executor(){ ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(3); executor.setMaxPoolSize(10); executor.setQueueCapacity(100); return executor; } @Bean public SimpleApplicationEventMulticaster applicationEventMulticaster(ThreadPoolTaskExecutor executor){ SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster(); multicaster.setTaskExecutor(executor); return multicaster; }
自定义listener进行解析
public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A48.class); SmsService bean = context.getBean(SmsService.class); for (Method method : SmsService.class.getMethods()) { if(method.isAnnotationPresent(MyListener.class)){ ApplicationListener listener = new ApplicationListener() { @Override public void onApplicationEvent(ApplicationEvent event) { try { method.invoke(bean,event); } catch (Exception e) { e.printStackTrace(); } } }; context.addApplicationListener(listener); } } context.close(); } @Component @Slf4j static class SmsService{ @MyListener public void listener(ApplicationEvent event){ log.info("发送短信...."); } }
(图片来源网络,侵删)
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。