【问题标题】:How to exclude bean from loading?如何从加载中排除bean?
【发布时间】:2016-11-12 03:36:39
【问题描述】:

我在将外部库与 Spring 集成时遇到问题。它包含一个用@Configuration 注释的类,它有一个用@Bean 注释的方法。我不希望它被实例化(它不是必需的,并且引入了对 Spring Boot 的依赖,我不使用它。

不幸的是,这个@Configuration-annotated 类在库的其他地方使用(由类类型而不是接口类型要求,所以我需要完全实例化这个类)。

我从自动扫描中排除了它的包,我没有直接导入它。只需手动构建它并在自己的配置中注册为 bean。

所以,长话短说 - 我需要注册一个 bean,但将其从注释 scnanning 中排除(不处理它的 @Bean-annotated 方法)。有什么办法吗?

【问题讨论】:

  • 您可以参考以下链接。希望对您有所帮助。 stackoverflow.com/questions/18992880/…
  • @JSav 请阅读问题描述。我不是自动扫描包,而是手动创建一个 bean,只是因为它被注入到容器中,它正在被处理。
  • @RafałWrzeszcz,“注册一个没有注释扫描的 bean”是什么意思?那你怎么注册呢?您需要一个带有'@Bean'注释的方法来创建类的实例和实例,或者用'@Componen'、'@Service'等注释来注释类以进行注释扫描以找到它?
  • @ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = TheBean.class) ) 会帮助你吗?
  • @GokhanOner 我希望它被注册。

标签: java spring spring-mvc


【解决方案1】:

如果您的意思是您的 maven、gradle 中有库,那么您可以将 spring bean 排除在初始化之外。我找到了exclude @Component from @ComponentScan

@Configuration @EnableSpringConfigured
@ComponentScan(basePackages = {"com.example"}, excludeFilters={
@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE, value=Foo.class)})
public class MySpringConfiguration {}

如果你不想包含传递依赖,因此你不希望你的依赖添加它使用的其他依赖,你必须从你的依赖中排除它们(在 maven,gradle 中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-08
    • 2020-09-09
    • 2011-07-20
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    相关资源
    最近更新 更多