Java自定义注解(二)

上文介绍了如何自定义注解,本篇主要介绍如何使用注解

自定义注解

package com.example.annotaion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//注解保留到什么时候
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface CacheResult {

    //缓存key
    String key();

    //缓存名称
    String cacheName();

    //过期时间
    String expireDate() default "";

    //是否过期
    boolean expire() default false;
}

在另外一个controller里面使用这个注解

package com.example.controller;

import com.example.annotaion.CacheResult;
import org.springframework.stereotype.Controller;

@Controller
@CacheResult(key = "IndexController-class-key", cacheName = "IndexController-class-cacheName")
public class IndexController {

    @CacheResult(key = "IndexController-method-key", cacheName = "IndexController-method-cacheName")
    public String index() {
        return "hhh";
    }
}

通过JDK反射来实现获取注解

/**
     * 通过JDK的反射的方式来获取注解
     */
    @Test
    void testMyAnnotationByJDK() {
        Class<TestController> clazz = TestController.class;
        Class<CacheResult> annoClazz = CacheResult.class;
        //如果在TestController这个类上面使用了CacheResult这个注解
        if (clazz.isAnnotationPresent(annoClazz)) {
            CacheResult annotation = clazz.getAnnotation(annoClazz);
            System.out.println(annotation.key());
            System.out.println(annotation.cacheName());
        }
        Method[] methods = clazz.getMethods();
        //遍历所有的方法,如果这个方法上有这个注解,则获取这个注解
        for (Method method : methods) {
            if (method.isAnnotationPresent(annoClazz)) {
                CacheResult annotation = method.getAnnotation(annoClazz);
                System.out.println(annotation.key());
                System.out.println(annotation.cacheName());
            }
        }
    }

运行效果


IndexController-class-key
IndexController-class-cacheName
IndexController-method-key
IndexController-method-cacheName

通过spring容器来获取注解

首先需要实现spring的两个接口

package com.example.component;

import com.example.annotaion.CacheResult;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Set;

@Component
//实现了ApplicationContextAware接口,就可以获取到容器到上下文
//ApplicationListener<ContextRefreshedEvent>容器启动之后的监听器
public class MyComponent implements ApplicationContextAware, ApplicationListener<ContextRefreshedEvent> {

    ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Class<CacheResult> cacheResultClass = CacheResult.class;
        //spring容器启动之后,spring上下文获取有CacheResult注解的bean
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(cacheResultClass);
        //遍历这些有CacheResult注解的bean
        Set<Map.Entry<String, Object>> entries = beansWithAnnotation.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            String beanId = entry.getKey();//获取bean的名字
            Class<?> aClass = entry.getValue().getClass();//获取bean的类对象
            System.out.println("在spring容器中,使用CacheResult注解的beanId:"+beanId);
            System.out.println("在spring容器中,使用CacheResult注解的bean名称:"+aClass.getName());


            //获取注解类实例
            CacheResult annotation = AnnotationUtils.findAnnotation(aClass, cacheResultClass);
            System.out.println(annotation.key());
            System.out.println(annotation.cacheName());


            Method[] methods = aClass.getMethods();
            //遍历带有cacheResult注解的类中的所有方法
            for (Method method : methods) {
                CacheResult annotation1 = AnnotationUtils.findAnnotation(method, cacheResultClass);
                if (annotation1 != null) {
                    System.out.println(annotation1.key());
                    System.out.println(annotation1.cacheName());
                }
            }
        }

    }

    public void test() {
        System.out.println("TestComponent中的test方法,没有实际意义");
    }
}

注入这个component


@SpringBootTest
class StudyAnnotationApplicationTests {

    @Resource
    private MyComponent myComponent;
    @Test
    void TestMyAnnotationBySpring() {
        myComponent.test();
    }
}

### 运行效果
 ```shell
在spring容器中,使用CacheResult注解的beanId:indexController
在spring容器中,使用CacheResult注解的bean名称:com.example.controller.IndexController
IndexController-class-key
IndexController-class-cacheName
IndexController-method-key
IndexController-method-cacheName
在spring容器中,使用CacheResult注解的beanId:testController
在spring容器中,使用CacheResult注解的bean名称:com.example.controller.TestController$$EnhancerBySpringCGLIB$$3d4dbf28
class_key
class_cacheName
method_key
method_cacheName
2021-03-04 15:47:11.943  INFO 15259 --- [           main] c.e.StudyAnnotationApplicationTests      : Started StudyAnnotationApplicationTests in 1.645 seconds (JVM running for 2.422)

TestComponent中的test方法,没有实际意义

2021-03-04 15:47:12.132  INFO 15259 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

micro_cloud_fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值