[英]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.