自定义注解初探

一直都觉得注解是很难理解的概念,今天尝试着自己也写了一个注解,才发现有的时候真不能依靠感觉或想象,“绝知此事要躬行”,要想知道注解的用法,还要写起来才行。

所以就先从一个例子开始吧。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Component
public @interface ServiceAnnotation {
    Class<?> value();
}

自定义了一个注解 ServiceAnnotation 。要想了解注解定义的规则,最好的办法是看源码。
比如:

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     * 注解将会被编译器忽略
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     * 注解将被编译器记录在class文件中,但在运行时不会被虚拟机保留,这是一个默认的行为
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *注解将被编译器记录在class文件中,而且在运行时会被虚拟机保留,因此可以通过反射方式读取它们
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

应用:所有实现Service接口的类上全部应用@ServiceAnno注解

@ServiceAnno(Service.class)
public class ServiceImpl implements Service {

}

为何要使用自定义注解。本次使用注解的目的是在spring的包扫描中找到Service接口的实现类。因此在Service的实现类上加上@ServiceAnnotation ,spring扫描包时,通过@ServiceAnnotation 注解,便可以获取实现Service接口的所有类。

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容