SpringMVC Annotation自定义注解使用笔记


https://www.cnblogs.com/shipengzhi/articles/2716004.html

https://www.cnblogs.com/magicalSam/p/7161942.html 


注解是Java 1.5引入的,目前已被广泛应用于各种Java框架,如Hibernate,Jersey,Spring。注解相当于是一种嵌入在程序中的元数据,可以使用注解解析工具或编译器对其进行解析,也可以指定注解在编译期或运行期有效。


step1:自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface ApiLog {
    String type();
    String name();
}


  • 注解方法不能有参数。
  • 注解方法的返回类型局限于原始类型,字符串,枚举,注解,或以上类型构成的数组。
  • 注解方法可以包含默认值。
  • 注解可以包含与其绑定的元注解,元注解为注解提供信息,有四种元注解类型:

1. @Documented – 表示使用该注解的元素应被javadoc或类似工具文档化,它应用于类型声明,类型声明的注解会影响客户端对注解元素的使用。如果一个类型声明添加了Documented注解,那么它的注解会成为被注解元素的公共API的一部分。

2. @Target – 表示支持注解的程序元素的种类,一些可能的值有TYPE, METHOD, CONSTRUCTOR, FIELD等等。如果Target元注解不存在,那么该注解就可以使用在任何程序元素之上。

3. @Inherited – 表示一个注解类型会被自动继承,如果用户在类声明的时候查询注解类型,同时类声明中也没有这个类型的注解,那么注解类型会自动查询该类的父类,这个过程将会不停地重复,直到该类型的注解被找到为止,或是到达类结构的顶层(Object)。

4. @Retention – 表示注解类型保留时间的长短,它接收RetentionPolicy参数,可能的值有SOURCE, CLASS, 以及RUNTIME。



step2:定义Aspect

@Aspect
@Component
public class AnnotationAspect {

//    @Pointcut("execution(public * com.demo.annotation.AnnotationTest.display(..))")
//    private void upUserPointCutMethod() {
//    }
//    @Around("upUserPointCutMethod()")
    @Around( value="@annotation(com.demo.annotation.ApiLog)")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        //取method
        MethodSignature signature=(MethodSignature) pjp.getSignature();
        Method targetMethod=signature.getMethod();
        //取method上annotation
        ApiLog apiLog=targetMethod.getAnnotation(ApiLog.class);
        if(apiLog!=null){
            //注解信息
            System.out.println("ApiLog name:"+apiLog.name()+" type:"+ apiLog.type());
        }
        //取parameters
        Object[] objects = pjp.getArgs();
        //取parameters里的注解
        Annotation[][] annotations = targetMethod.getParameterAnnotations();

        Object result = pjp.proceed();

        return result;
    }
}



step3:

配置spring-controller.xml中

 <aop:aspectj-autoproxy proxy-target-class="true" />
 <context:component-scan base-package="com.demo.annotation"></context:component-scan>

自定义注解使用与测试 

@Component
public class AnnotationTest {
    @ApiLog(type = "method", name ="display" )
    public void display(){
        System.out.println("display");
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-controller.xml");
        AnnotationTest injectClass=context.getBean(AnnotationTest.class);
        //AnnotationTest injectClass =new AnnotationTest();
        injectClass.display();
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值