自定义注解

自定义注解

一、注解概念

1.1 注解的官方定义

An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.

1.2 注解的使用范围

Annotations have a number of uses, among them:Information for the complier - Annotations can be used by the compiler to detect errors or suppress warnings.Compiler-time and deployment-time processing - Software tools can process annotation information to generate code, XML files, and so forth.Runtime processing - Some annotations are available to be examined at runtime.

二、元注解

元注解是专门修饰注解的注解。它们都是为了更好的设计自定义注解的细节而专门设计的。

2.1 @Target:表示该注解可以用于什么地方,就是注解使用的目标对象

@Target(ElementType.TYPE) :类、接口(包括注解类型)或enum声明。
@Target(ElementType.FIELD):字段、枚举的常量。
@Target(ElementType.METHOD):METHOD:方法声明。
@Target(ElementType.PARAMETER):方法参数声明。
@Target(ElementType.CONSTRUCTOR):构造器的声明。
@Target(ElementType.LOCAL_VARIABLE):局部变量声明。
@Target(ElementType.ANNOTATION_TYPE):注解类型声明。
@Target(ElementType.PACKAGE):包声明。

2.2 @Retention:表示需要在什么级别保存该注解信息,就是注解保存的策略。

@Retention(RetentionPolicy.SOURCE):注解将被编译器丢弃。
@Retention(RetentionPolicy.CLASS):注解在class文件中可用,在jvm中丢弃。
@Retention(RetentionPolicy.RUNTIME):jvm在运行期也保留注解,可以通过反射机制来读取注解的信息。

2.3 @Documented:将此注解包含在Javadoc中。

2.4 @Inherited:允许子类继承父类中的注解。

三、自定义注解配合 Spring AOP 实现方法参数注入

/**
 * 自定义注解
 * 配置输出的信息
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface OutMessage {
    String message() default "";
}
/**
 * 切面类
 */
@Aspect
@Component
public class OutMessageAspect {
    /**
     * 定义切点
     */
    @Pointcut("@annotation(cn.mejiwef.annotationdemo.selftest.OutMessage)")
    public void messagePoint() {
    }

    @Around("messagePoint()")
    public Object setMessage(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        MethodSignature ms = (MethodSignature) signature;
        OutMessage annotation = ms.getMethod().getAnnotation(OutMessage.class);
        String message = annotation.message();
        return pjp.proceed(new Object[]{message});
    }
}
// 方法上使用自定义注解
@OutMessage(message = "hello world")
public void p(String message) {
    System.out.println(message);
}

posted on 2019-10-09 16:36  宁静致远呀  阅读(344)  评论(0编辑  收藏  举报

导航