首页 > 编程知识 正文

自定义注解java,java注解大全

时间:2023-05-06 06:06:57 阅读:147835 作者:2059

Spring Boot中经常使用@Inherited注释。 让我们看看这个注释的用法,注释的源代码:

packagejava.lang.annotation;/* * indicatesthatanannotationtypeisautomaticallyinherited.if

* aninheritedmeta-annotationispresentonanannotationtype

* declaration,andtheuserqueriestheannotationtypeonaclass

* declaration,andtheclassdeclarationhasnoannotationforthistype,

* then the class ' ssuperclasswillautomaticallybequeriedforthe

* annotation type.thisprocesswillberepeateduntilanannotationforthis

* type is found,orthetopoftheclasshierarchy (object ) )。

* is reached.ifnosuperclasshasanannotationforthistype,then

* thequerywillindicatethattheclassinquestionhasnosuchannotation。

*

*

notethatthismeta-annotationtypehasnoeffectiftheannotated

* typeisusedtoannotateanythingotherthanaclass.note also

* thatthismeta-annotationonlycausesannotationstobeinherited

*来自super classes; annotationsonimplementedinterfaceshaveno

*效率。

*

*@authorJoshua Bloch

*@since1.5

* @ jls9.6.3.3@ inherited */@ documented

@ retention (retention policy.runtime ) )。

@ target (element type.annotation _ type )公共@ interface inherited {

}

注释作用:

某个注释类在该类中定义@Inherited注释时,例如SpringBoot的@SpringBootApplication注释、@SpringBootApplication注释类为@Inherited

@target(elementtype.type ) )。

@ retention (retention policy.runtime ) )。

@Documented

@Inherited

@SpringBootConfiguration

@EnableAutoConfiguration

@ components can (exclude filters={

@filter(type=filtertype.custom,classes=typeexcludefilter.class )、

@filter(type=filtertype.custom,classes=autoconfigurationexcludefilter.class ) ) public @ interfacespringbotappppotapppom

//…省略}

那么,使用这个注释的我们有自己开发的类。 例如:

@SpringBootApplication

@Servicepublic classPerson {

}

然后有一个类Employee继承了Person

publicclassemployeextendsperson {

}

现在,在确定Employee类中是否存在@SpringBootApplication时,将通过代码进行验证:

@Testpublic voidtest1 () ) {

Class clazz=Employee.class; clazz.isannotationpresent (springbootapplication.class ) }

system.out.println('true ' );

}

}

上面的测试用例运行会在true (即子类)中找到@SpringBootApplication,同样,如果在上面的代码中检查Employee类中是否有Spring的@Service注释,则会发现这样就明白了@Inherited评论的意图了吧。

经过这样的分析,如果再次阅读JDK文档,会更容易理解。 否则,会觉得有点绕圈子。 @interface注释的中文文档如下所示。

指示注释类型将自动继承。 如果注释类型声明中存在inherited meta注释,并且用户在类声明中查询该注释类型,并且该类声明中没有该类型的注释,则在该类的超类中自动查询该注释类型。 重复此过程,直到找到此类型的注释或到达类层次的顶级(Object )。 如果超类没有此类型的注释,则查询将指示当前类没有此类注释。

请注意,如果使用的注释类型不是注释类,则此元注释类型无效。 另外,请注意,此元注释只是从超类继承注释。 对实现的接口的注释无效。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。