[英]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 . 除非注释类型具有@Inherited元注释,否则不会继承Java注释: 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. Spring的
@Component
注释上没有@Inherited ,因此您需要在每个组件类上添加注释。 @Service, @Controller and @Repository neither. @ Service,@ Controller和@Repository都没有。
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
. 答案很长:有一个名为
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. 但是,正如您在spring源代码中看到的那样,
@Service
和@Scope
注释本身并未使用@Inherited
注释,因此类的@Service
和@Scope
的存在不会被其子类继承。
Maybe this is something that can be fixed in Spring. 也许这是可以在Spring中修复的东西。
I have this piece of code in my project and it works just fine, although it's not annotated as Service: 我在我的项目中有这段代码,它工作得很好,虽然它没有注释为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. 因此,您不需要在抽象类上添加注释,但即使您这样做,仍然必须在所有子类上添加注释,因为
@Component
或@Service
注释不会被继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.