动态添加Spring的事件监听
在实际项目中,有些事件可能需要动态添加监听器,比如从配置中加载
在Spring中好像没有可以指定事件添加监听器方法,都是根据类反射得到监听的事件类型
只能自己实现一下监听器了
public class DynamicSpringEventListener implements GenericApplicationListener { private final ApplicationListener<ApplicationEvent> delegate; @Nullable private final ResolvableType declaredEventType; public DynamicSpringEventListener(Class<? extends ApplicationEvent> eventClass, ApplicationListener<ApplicationEvent> delegate) { Assert.notNull(delegate, "Delegate listener must not be null"); this.delegate = delegate; this.declaredEventType = ResolvableType.forClass(eventClass); } public void onApplicationEvent(ApplicationEvent event) { this.delegate.onApplicationEvent(event); } public boolean supportsEventType(ResolvableType eventType) { return this.declaredEventType == null || this.declaredEventType.isAssignableFrom(eventType); } public boolean supportsSourceType(@Nullable Class<?> sourceType) { return true; } @Override public int getOrder() { return (this.delegate instanceof Ordered ? ((Ordered) this.delegate).getOrder() : Ordered.LOWEST_PRECEDENCE); } @Override public String getListenerId() { return (this.delegate instanceof SmartApplicationListener ? ((SmartApplicationListener) this.delegate).getListenerId() : ""); } }
使用方法
package com.test;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class TestPublisher {
@Autowired
private ApplicationEventMulticaster eventMulticaster;
@Autowired
private ApplicationEventPublisher eventPublisher;
public void addEventListener(Class<? extends ApplicationEvent> eventClass) {
System.err.println("add event for class " + eventClass.getSimpleName());
DynamicSpringEventListener eventListener = new DynamicSpringEventListener(eventClass, event -> {
System.err.println("on test event");
});
eventMulticaster.addApplicationListener(eventListener);
}
}
根据需要动态添加
@PostConstruct
public void init() {
Class[] events = new Class[] {TestApplicationEvent.class};
for (Class clazz : events) {
addEventListener(clazz);
}
}
浙公网安备 33010602011771号