如何在扫描期间排除一个组件?

hujrc8aj  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(320)

我需要使用一个jar依赖项。jar中有一个组件干扰了spring引导应用程序的一部分。我需要排除这一个组件,而更改jar依赖中的组件定义目前是不可能的。
我尝试了以下操作,但是没有成功,bean仍然被加载:

@SpringBootApplication
@ComponentScan(useDefaultFilters = false, excludeFilters = [Filter(type = FilterType.ASSIGNABLE_TYPE, classes = [SomeBean::class])])

bean定义为:

@RestController
class SomeBean {

注意:这些片段在kotlin中。

ltqd579y

ltqd579y1#

你能做如下的事情跳过创建bean吗?

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor {

  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {}

  @Override
  public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
    registry.removeBeanDefinition("myBeanName");
  }
}
lhcgjxsq

lhcgjxsq2#

试试这个

@SpringBootApplication(exclude = { SomeBean.class })
tvmytwxo

tvmytwxo3#

不是吗 @Bean / @Component /等等,或者 @Configuration 上面有任何条件注解(例如: @ConditionalOnMissingBean , @ConditionalOnProperty 等等)?这将是解决这个问题的正确办法。你能要求维修人员添加适当的条件吗?这样你(和其他用户)就不需要破解了。
但是有一个可怕的黑客:beandefinitionregistry#removebeandefinition

相关问题