【第四十八讲】事件-监听器

第四十八讲 事件-监听器

  1. 实现ApplicationListener 接口
  2. 通过@EvenListener 方法
  3. @EventListener 原理

ApplicationListener 接口

事件

static class MyEvent extends ApplicationEvent {
    public MyEvent(Object source) {
        super(source);
    }
}

主线

@Component
static class MyService{
    @Autowired
    private ApplicationEventPublisher publisher; // applicationContext
    public void doBusiness() {
        log.debug("主线业务");
        // 主线业务完成后需要做一些支线业务,下面是问题代码
        publisher.publishEvent(new MyEvent("MyService.doBusiness()"));
    }
}

------------------------------------------
    public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A48_1.class);
    context.getBean(MyService.class).doBusiness();
    context.close();

}    

解耦后操作

@Component
static class SmsApplicationListener implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent event) {
        log.debug("发送短信");
    }
}

----------------------------------------------------------------------------
@Component
static class EmailApplicationListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        log.debug("发送邮件");
    }
}

在这里插入图片描述

通过@EvenListener 方法实现

只需要修改解耦部分

@Component
static class SmsApplicationListener implements ApplicationListener<MyEvent> {

    @Override
    public void onApplicationEvent(MyEvent event) {
        log.debug("发送短信");
    }
}

----------------------------------------------------------------------------
@Component
static class EmailApplicationListener implements ApplicationListener<MyEvent> {
    @Override
    public void onApplicationEvent(MyEvent event) {
        log.debug("发送邮件");
    }
}
@Component
static class SmsApplicationListener {
    @EventListener
    public void listener(MyEvent event) {
        log.debug("发送短信");
    }
}

@Component
static class EmailApplicationListener {
    @EventListener
    public void listener(MyEvent event) {
        log.debug("发送邮件");
    }
}

异步执行线程

@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;
}

在这里插入图片描述

@EventListener 原理

定义自己注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyListener {
}

替换注解

@Component
static class SmsApplicationListener {
    @MyListener
    public void listener(MyEvent event) {
        log.debug("发送短信");
    }
}

@Component
static class EmailApplicationListener {
    @MyListener
    public void listener(MyEvent event) {
        log.debug("发送邮件");
    }
}
 public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A48_3.class);
        SmsApplicationListener bean = context.getBean(SmsApplicationListener.class);

        for (Method method : SmsApplicationListener.class.getMethods()) {
            if(method.isAnnotationPresent(MyListener.class)){
                ApplicationListener listener = new ApplicationListener() {
                    @Override
                    public void onApplicationEvent(ApplicationEvent event) {
                        // 监听器 方法需要的事件类型
                        System.out.println("事件---"+event);
                        Class<?> evenType = method.getParameterTypes()[0];// 
                        if(evenType.isAssignableFrom(event.getClass())){
                            try {
                                method.invoke(bean,event);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                context.addApplicationListener(listener);
            }
        }

        context.getBean(MyService.class).doBusiness();
        context.close();

    }

在这里插入图片描述

context.close 也会调用 ApplicationListener,所以反射的时候需要进行判断,不然会报错

在这里插入图片描述

在 SmartInitializingSingleton(所有单例初始化完成后),解析每个单例 bean

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A48_3.class);

    for (String name : context.getBeanDefinitionNames()) {
        Object bean = context.getBean(name);
        for (Method method : bean.getClass().getMethods()) {
            if(method.isAnnotationPresent(MyListener.class)){
                ApplicationListener listener = new ApplicationListener() {
                    @Override
                    public void onApplicationEvent(ApplicationEvent event) {
                        // 监听器 方法需要的事件类型
                        System.out.println("事件---"+event);
                        Class<?> evenType = method.getParameterTypes()[0];//
                        if(evenType.isAssignableFrom(event.getClass())){
                            try {
                                method.invoke(bean,event);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                context.addApplicationListener(listener);
            }
        }

    }

    context.getBean(MyService.class).doBusiness();
    context.close();

}

在这里插入图片描述

利用SmartInitializingSingleton进行优化

public static void main(String[] args) {
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(A48_3.class);
    context.getBean(MyService.class).doBusiness();
    context.close();

}

-----------------
@Bean
public SmartInitializingSingleton smartInitializingSingleton(ConfigurableApplicationContext context){
    return new SmartInitializingSingleton() {
        @Override
        public void afterSingletonsInstantiated() {
            for (String name : context.getBeanDefinitionNames()) {
                Object bean = context.getBean(name);
                for (Method method : bean.getClass().getMethods()) {
                    if(method.isAnnotationPresent(MyListener.class)){
                        ApplicationListener listener = new ApplicationListener() {
                            @Override
                            public void onApplicationEvent(ApplicationEvent event) {
                                // 监听器 方法需要的事件类型
                                System.out.println("事件---"+event);
                                Class<?> evenType = method.getParameterTypes()[0];//
                                if(evenType.isAssignableFrom(event.getClass())){
                                    try {
                                        method.invoke(bean,event);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        };
                        context.addApplicationListener(listener);
                    }
                }

            }
        }
    };
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值