spring annotation inheritance

@Autowired/@Inject (method)

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.

@Transactional(class/method)

the @Transactionalannotation has @Inherited.

From the docs:

Indicates that an annotation type is automatically inherited. If an Inherited meta-annotation is present on an annotation type declaration, and the user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class’s superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached. If no superclass has an annotation for this type, then the query will indicate that the class in question has no such annotation.

Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class. Note also that this meta-annotation only causes annotations to be inherited from superclasses; annotations on implemented interfaces have no effect.

Docs of @Transactional:

@Target(value={METHOD,TYPE})
@Retention(value=RUNTIME)
@Inherited
@Documented
public @interface Transactional
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s