Inherit @Component in Spring

11,592

Solution 1

You can use a ComponentScan.Filter for this.

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

This will allow Spring to autowire your Child, without you having to attach an annotation to Child directly.

Solution 2

To answer the question posed under the accepted answers "How do do in XML" This is taken from Spring in Action with a trivial example by me.

Annotate the base class with component, add a qualifier

@Component
@InstrumentQualifier("TUBA")
public class Instrument {}

Qualify the subclass - NOTE- No need for @component

@InstrumentQualifier("GUITAR")
public class Guitar extends Instrument {}

Inject it like so

@Autowired
@InstrumentQualifier("GUITAR")
public void setInstrument(Instrument instrument) {this.instrument =instrument;}

In context.xml, add an include filter for assignable type

<context:component-scan base-package="some.pkg">
<context:include-filter type="assignable" expression="some.pkg.Instrument"/>
</context:component-scan>

The type and expression work as define the strategy here. You could also use the type as "annotation" and the expression would be the path to where the custom qualifier is defined to achieve the same goal.

Share:
11,592
Aleks Ya
Author by

Aleks Ya

Updated on June 09, 2022

Comments

  • Aleks Ya
    Aleks Ya about 2 years

    I have a hierarchy of classes. I want mark them with @Component. I'm trying to mark only the parent class. I expect Spring will mean childs as components too. But it doesn't happen.

    I tried to use custom @InheritedComponent annotation like described here. It doesn't work.

    I wrote an unit test. It fails with: "No qualifying bean of type 'bean.inherit.component.Child' available". Spring version is 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);
        }
    }
    
  • Kevin Orriss
    Kevin Orriss almost 6 years
    Would you know how to do this in XML?