Inherit @Component in Spring

I have a class hierarchy. I want to tag them with @Component . I am trying to mark only the parent class. I expect Spring to mean baby components too. But that doesn't happen.

I tried to use custom annotation @InheritedComponent

as described here . This does not work.

I wrote a unit test. He fails: "No qualifying bean of type 'bean.inherit.component.Child' available"

. Spring version 4.3.7.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Inherited
public @interface InheritedComponent {}

@InheritedComponent
class Parent { }

class Child extends Parent {
}

@Configuration
@ComponentScan(basePackages = "bean.inherit.component")
class Config {
}

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class InheritComponentTest {

    @Autowired
    private Child child;

    @Test
    public void name() throws Exception {
        assertNotNull(child);
    }
}

      

+3


source to share


1 answer


You can use ComponentScan.Filter for this.

@ComponentScan(basePackages = "bean.inherit.component", 
includeFilters = @ComponentScan.Filter(InheritedComponent.class))

      



This will allow Spring to auto-increment your Child, without having to bind the annotation to Child directly.

+5


source







All Articles