spring - 在 BeanDefinitionRegistry 中注册后如何阻止 bean 实例化
问题描述
在 BeanDefinitionRegistry 中注册后,我需要从实例化中取消注册几个 bean。我需要在某些情况下这样做。
如果我写这样的代码
@Component
public class DomainConfig implements BeanDefinitionRegistryPostProcessor {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
beanDefinitionRegistry.removeBeanDefinition("createBlahExporter");
beanDefinitionRegistry.removeBeanDefinition("createBlahDataSource");
beanDefinitionRegistry.removeBeanDefinition("createBlahMonitorSettings");
beanDefinitionRegistry.removeBeanDefinition(("com.blah.BlahConfiguration));
}
}
我收到以下错误:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field blahDataExporter in com.blah.BlahConfiguration required a bean of type
'com.blah.export.Exporter' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
The following candidates were found but could not be injected:
- Bean method 'createProviderDumpExporter' in 'ProviderDumperConfig' not loaded because
@ConditionalOnProperty (providers.dump.local.enabled=true) found different value in property
'providers.dump.local.enabled'
Action:
Consider revisiting the entries above or defining a bean of type 'com.harman.inca.export.Exporter' in
your configuration.
即使从这里移走,也有人,在某处拿着注册的名字。如何从已注册的 bean 集中删除 bean。
解决方案
您没有指定什么是 ConfigFactory,但可以考虑添加您自己的 Conditional 实现。
自定义条件可以从这个配置工厂读取定义,并且绑定到这个自定义条件谓词的注释可以放在您计划“取消注册”的 bean 上。使用这种方法,它们将不会在应用程序上下文中注册,因此您无需取消注册它们。
有很多关于如何实现这些自定义条件的教程:
从原理上讲,您应该:
- 实现条件的逻辑
class OnConfigFactoryCondition implements Condition {
@Override
public boolean matches(
ConditionContext context,
AnnotatedTypeMetadata metadata) {
// analyze the value from ConfigFactory whatever it is
Return true /false
}
}
- 创建一个绑定到您的条件的条件注释:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Conditional(OnConfigFactoryCondition.class)
public @interface ConditionalOnConfigFactory {
...
}
然后,您可以将此注释放在@Component
定义旁边,或者@Bean
如果您使用的是 Java Config
推荐阅读
- python - 无论如何要加载 SDF 文件并获取诸如 mols、inchi 和试剂之类的详细信息?
- reactjs - React 中动态选项卡的最佳组件结构是什么?
- docker - 为什么在不指向主机上的实际文件夹时要声明两次 docker-compose 卷?
- ruby-on-rails - 如何在 Heroku 上部署和访问 swagger-ui
- r - 尝试在 R 中动态命名数据帧时,如何解决“找不到函数”deparse<-”|“as.name<-”|“eval<-””错误?
- nginx - SoundCloud 如何流式传输他们的 mp3 文件?
- jquery - 切换 img src 文件路径
- macos - 向下箭头是什么键盘快捷键?
- mysql - 如何使用mysql spring和mybatits访问同一数据库的多个数据库模式
- angular - 在 mat-stepper 完成后防止新的 formControl 无效