有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

已在库中创建类:

@Component
public class CommonComponent{}

在使用库的一个子应用程序中,我添加了一个子组件:

@Component
public class ChildComponent extends CommonComponent{}

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


共 (2) 个答案

  1. # 1 楼答案

    实现这一点的一种方法是利用Spring Boot具有的^{}注释。当与@Configuration类中的bean定义相结合时,我们可以告诉Spring仅在它还没有bean的情况下定义我们的bean

    这是未经测试的:

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

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

  2. # 2 楼答案

    创建子组件时,请放置@Primary注释

    Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency

    所以你会有

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

    在您的服务中,autowire CommonComponent类型和spring将注入ChildComponentCommonComponent