Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit @Component in Spring

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);
    }
}
like image 601
Aleks Ya Avatar asked Apr 03 '17 23:04

Aleks Ya


2 Answers

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.

like image 65
Gary Avatar answered Nov 19 '22 23:11

Gary


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.

like image 27
Nanotron Avatar answered Nov 19 '22 23:11

Nanotron