一,通过反射工具包
<!-- 反射工具包 -->
<dependency>
<groupId>net.oneandone.reflections8</groupId>
<artifactId>reflections8</artifactId>
<version>0.11.7</version>
</dependency>
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
Reflections reflections = new Reflections(AdminApplication.class);
// 获取一个接口的所有实现类
Set<Class<? extends AppStartListener>> subTypes = reflections.getSubTypesOf(AppStartListener.class);
// 循环执行所有实现类的方法 可以用 if(aClass instanceof AAppStartListener) 判断具体是哪个实现
subTypes.forEach(aClass -> {
applicationContext.getBean(aClass).onApplicationEvent(applicationReadyEvent);
});
}
二,工厂模式
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
applicationContext.getBean(appStartListenerFactory("A").getClass()).onApplicationEvent(applicationReadyEvent);
}
public AppStartListener appStartListenerFactory(String platform) {
if (StringUtils.equals("A", platform)) {
return new AAppStartListenerImpl();
} else if (StringUtils.equals("B", platform)) {
return new BAppStartListenerImpl();
} else if (StringUtils.equals("C", platform)) {
return new CAppStartListenerImpl();
}else {
return new AppStartListenerImpl();
}
}
|