tags:

views:

188

answers:

1

The @Resource annotation for a service is not injecting a subclass unless I explicitly include the @Component annotation in the subclass. Is there a way to request a subclass be "wired" with the parent @Resource without requiring annotations in each child class? The way I discovered this was by creating a subclass and failing to include the @Component annotation. I was quickly faced with the dreaded NPE.

Peace, Scott

+1  A: 

@Component annotation works only for the class where it's declared, not for its subclasses (for performance reasons, I guess: otherwise it would require traversing of all ancestors for each class being scanned).

As a workaround, you can declare an assignable filter for your parent class in <context:component-scan>:

<context:component-scan base-package = "...">
    <context:include-filter type = "assignable" expression = "... your parent class ..." />
</context:component-scan>
axtavt
Thanks brother! I assume you mean descendants of the parent class? Also, would this include filter require specifying all classes that might have descendant classes that are not annotated with @Component? This would be awkward and more difficult than adding the annotation! I suppose now is a good time to read about context:include-filter.
stanlick
@stanlick: I mean that to achieve the desired behaviour Spring should either search all ancestors of each class for `@Component` annotation, or traverse all descendants of `@Component`-annotated class. Startup speed would suffer in both cases. And yes, I meant a separate filter declarations for each parent class, because I can't see any other ways, except for `@Component` at each child class.
axtavt
Great explanation! Yeah, adding (the redundant) @Component results in appropriate injections in child classes but seems to be a little silly. To me it's like "double" configuration. If Foo extends Bar and Bar is injected, Foo should be too as a result of Foo BEING-A Bar.
stanlick