Announcement Announcement Module
Collapse
No announcement yet.
@Inject/@Autowired inheritance Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • @Inject/@Autowired inheritance

    Hello Spring users,

    @Inject and @Autowired are not @Inherited, but for soem reason injection using these annotations works on inherited (setter) methods.

    Can someone please explain what was the reason for @Inject/@Autowired not to be @Inherited?

    Also, since injection with @Inject/@Autowired works for inherited methods, is my expectation wrong that it shouldn't since these annotations are not @Inherited, or is Spring doing more than it should?

    Can someone please explain (or point me to some Java annotation documentation), in case @Inject/@Autowired along existing targets also had ElementType.ANNOTATION_TYPE as their @Target, if I created a cusom @InheritedInject annotation annotated with @Inherited and @Inject, would it be detected as @Inject?

    I'm using Spring 3.1 M1.

    Regards,
    Stevo.

  • #2
    When you use @Inherited on a class annotation, this means that when that annotation is queried on a non-annotated subclass, the Java will look for it in the superclass.

    When you use @Inherited on a method annotation, this means that when that annotation is queried on a non-annotated method overridden in subclass, Java will look for it in the superclass.

    If your setter method is annotated with @Autowired on the superclass, but the setter method is not overridden in subclass (which is usually the case), the annotation does not need to be @Inherited to be found when you look for annotated methods into the subclass.

    Spring looks for all annotated setter methods in the class hierarchy. If a setter is annotated with @Autowired in the superclass and is overridden in the subclass without the @Autowired annotation, then Spring will not detect it and will not inject the dependency.

    Code:
    class A {
      @Autowired setFirst(First f) {}
      @Autowired setSecond(Second s) {}
    }
    
    class B extends A {
      @Overrides setFirst(First f) {}
    }
    In a bean definition declared as A, both setFirst() and setSecond() will be invoked, while in a bean definition declared as B, only setSecond() will be invoked, because setFirst() is overridden without @Autowired.
    This behaviour is not spring-related, but java-related.

    Comment

    Working...
    X