Java 我可以扩展一个@Component并创建另一个@Component类,并且一次只能使用一个吗?

Java 我可以扩展一个@Component并创建另一个@Component类,并且一次只能使用一个吗?,java,spring-boot,inheritance,Java,Spring Boot,Inheritance,我有一个库jar,我想提供给许多应用程序。我想要的行为是在库中创建一个公共spring组件类。如果在应用程序中,同一组件未扩展,则使用公共组件;如果在应用程序中进行了扩展,则使用扩展组件(子类)。这可能吗仅当该类的子级不存在时才创建CommonComponent 我使用的是Java1.8,Springboot2.0 已在库中创建类: @Component public class CommonComponent{} 在使用库的一个子应用程序中,我添加了一个子组件: @Component pub

我有一个库jar,我想提供给许多应用程序。我想要的行为是在库中创建一个公共spring组件类。如果在应用程序中,同一组件未扩展,则使用公共组件;如果在应用程序中进行了扩展,则使用扩展组件(子类)。这可能吗仅当该类的子级不存在时才创建CommonComponent

我使用的是Java1.8,Springboot2.0

已在库中创建类:

@Component
public class CommonComponent{}
在使用库的一个子应用程序中,我添加了一个子组件:

@Component
public class ChildComponent extends CommonComponent{}

我希望创建一个组件ChildComponent;但是在上面的场景中,创建了2个组件-CommonComponent和ChildComponent。

当您创建子组件时,put
@Primary
注释

指示当多个候选项有资格自动关联单值依赖项时,应优先考虑bean

所以你会有

@Primary
@Component
public class ChildComponent extends CommonComponent { /* ... */ }

在您的服务中,autowire
CommonComponent
类型和spring将注入
ChildComponent
CommonComponent
一种方法是利用spring Boot的注释。当与
@Configuration
类中的bean定义相结合时,我们可以告诉Spring仅在它还没有bean的情况下定义我们的bean

这是未经测试的:

@Configuration
public class CustomComponentConfiguration {

    @ConditionalOnMissingBean(CustomComponent.class)
    @Bean
    public CustomComponent customComponent() {
        return new CustomComponent();
    }
}

在本例中,当我们的
@配置运行时,Spring确定是否有任何其他bean是
自定义组件
。如果没有,它将执行
customComponent()
方法并定义返回的bean。因此,如果其他人定义了
子组件
,则不会调用此方法。

可能存在指定要扫描的包的配置。将您的组件放在另一个包中。CommonComponent上有@component的必要性是什么?它难道不是一个抽象类吗?@Pdem他们说CommonComponent是一个具体的类,因为它可以在子类不存在的情况下使用。所以它不能是抽象的…非常感谢你,托德。这对我有用。我不得不从父类(CommonComponent类)中删除@Component。我添加了如下配置类:
@configuration public class CustomComponentConfiguration{@ConditionalOnMissingBean@Bean public CommonComponent CommonComponent(){return new CommonComponent();}}}
谢谢Adrian。我试过这个;但只有当我必须在某个地方自动连接组件时,它才会起作用。我创建的是一个过滤器组件,因此我不会在代码中的任何地方显式地自动连接它。