繁体   English   中英

从抽象类继承注释?

[英]Inherit annotations from abstract class?

我可以以某种方式在抽象类上对一组注释进行分组,并且扩展此类的每个类都自动分配了这些注释吗?

至少以下不起作用:

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


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

答案是不

除非注释类型具有@Inherited元注释,否则不会继承Java注释: https//docs.oracle.com/javase/7/docs/api/java/lang/annotation/Inherited.html

Spring的@Component注释上没有@Inherited ,因此您需要在每个组件类上添加注释。 @ Service,@ Controller和@Repository都没有。

简短的回答是:使用您在示例中提到的注释, 没有

答案很长:有一个名为java.lang.annotation.Inherited的元注释。 如果注释本身使用此批注进行批注,那么当使用它对类进行批注时,其子类也会通过暗示自动对其进行批注。

但是,正如您在spring源代码中看到的那样, @Service@Scope注释本身并未使用@Inherited注释,因此类的@Service@Scope的存在不会被其子类继承。

也许这是可以在Spring中修复的东西。

我在我的项目中有这段代码,它工作得很好,虽然它没有注释为Service:

public abstract class AbstractDataAccessService {

    @Autowired
    protected GenericDao genericDao;


}

@Component
public class ActorService extends AbstractDataAccessService {

    // you can use genericDao here

}

因此,您不需要在抽象类上添加注释,但即使您这样做,仍然必须在所有子类上添加注释,因为@Component@Service注释不会被继承。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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