实现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<MyEvent>{
@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("发送短信....");
}
}