简体   繁体   中英

Inherit annotations from abstract class?

Can I somehow group a set of annotations on an abstract class, and every class that extends this class has automatically assigned these annotations?

At least the following does not work:

@Service
@Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
class AbstractService


class PersonService extends AbstractService {
    @Autowired //will not work due to missing qualifier annotation
    private PersonDao dao;
}

The answer is: no

Java annotations are not inherited unless the annotation type has the @Inherited meta-annotation on it: https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/Inherited.html .

Spring's @Component annotation does not have @Inherited on it , so you will need to put the annotation on each component class. @Service, @Controller and @Repository neither.

The short answer is: with the annotations that you mentioned in your example, no .

The long answer: there is a meta-annotation called java.lang.annotation.Inherited . If an annotation itself is annotated with this annotation, then when a class is annotated with it, its subclasses are also automatically annotated with it by implication.

However, as you can see in the spring source code, the @Service and @Scope annotation are not themselves annotated with @Inherited , so the presence of @Service and @Scope on a class is not inherited by its subclasses.

Maybe this is something that can be fixed in Spring.

I have this piece of code in my project and it works just fine, although it's not annotated as Service:

public abstract class AbstractDataAccessService {

    @Autowired
    protected GenericDao genericDao;


}

and

@Component
public class ActorService extends AbstractDataAccessService {

    // you can use genericDao here

}

So you don't need to put annotation on your abstract class but even if you do you will still have to put annotation on all subclass as @Component or @Service annotations are not inherited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM