上文介绍了如何自定义注解,本篇主要介绍如何使用注解
自定义注解
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