我终于找到了解决方案。它不是完美的,但在大多数情况下都可以使用。
最初,我意识到错误的插件意味着存在 链接 问题的插件,例如有人提供了没有运行时相关性的插件,或者插件版本与应用程序版本存在问题。
其次,我在Spring上下文初始化(准确地说是bean factory)中找到了一个钩子,该钩子可以在以下情况下注入代码:
All beandefinitions will have been loaded, but no beans will have been instantiatedyet. This allows for overriding or adding properties even to eager-initializing beans.-不管Spring文档信息如何,它还允许 删除 来自bean
factory的bean定义。通常,它可能不是安全的操作(最后,其他Bean可能需要删除的Bean),但我仅将其用于插件实例定义,默认情况下它们是独立的且自包含的。好了,足够讨论代码了,让我们看一下代码…;)
public class PluginQualifierProcessor implements BeanFactoryPostProcessor {private static final Logger LOGGER = LoggerFactory.getLogger(PluginQualifierProcessor.class);@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { String[] beanNamesForType = beanFactory.getBeanNamesForType(PluginInterface.class); List<String> beans = Arrays.asList(beanNamesForType) .stream() .collect(Collectors.toList()); for (String beanName : beans) { BeanDefinition bean = beanFactory.getBeanDefinition(beanName); if (!bean.hasConstructorArgumentValues()) { String className = bean.getBeanClassName(); try { tryToInstatiate(className); // we are interested only in runtime linkage errors that can happen if plugin is erroneous } catch (linkageError e) { LOGGER.error("plugin {} is erroneous. It will be discarded from context. {}", className, e); ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName); } } }}private void tryToInstatiate(String className) { try { Class<?> beanClass = Class.forName(className); beanClass.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { LOGGER.debug("skip exception while creating instance of {}. {}", className, e.getMessage()); }}}
关键片段是:
catch (linkageError e) { ((BeanDefinitionRegistry) beanFactory).removeBeanDefinition(beanName); }我们捕获linkageError(不是异常!),因为我们搜索的是残破的实现,并且正如Java文档所说的那样
linkageError的子类表明一个类对另一个类具有一定的依赖性。但是,前一类编译后,后一类发生了不兼容的变化
。
我发现,这也表明缺少依赖关系。一开始,我写道该解决方案并不完美。代码检查插件是否具有无参数构造函数以实例化它。如果插件没有一个-
无法检查。因此,我需要对插件提出其他要求-它们必须具有无参数的构造函数:)。



