Skip to content

Latest commit

 

History

History
102 lines (78 loc) · 2.85 KB

自定义注解.md

File metadata and controls

102 lines (78 loc) · 2.85 KB

如何实现自定义注解?

(1)继承 SpringFactoryImportSelector,模仿 EnableDiscoveryClientImportSelector(类注解)

(2)实现 BeanPostProcessor,spring所有的bean都过这个接口

(3)实现 ApplicationListener

(4)可以使用 AOP

1. 自定义注解类

这里定义一个方法注解:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface 自定义注解类 {

}

2. 实现 ApplicationListener

@Component
public class 扫描类 implements ApplicationListener<ApplicationEvent> {

  private static final AtomicBoolean START = new AtomicBoolean(false);

  @Override
  public void onApplicationEvent(ApplicationEvent event) {

      if (event instanceof ContextRefreshedEvent) { // 应用刷新
          // 对自定义注解的处理,只进行一次
          if (START.compareAndSet(false, true)) {
              // 关键代码 try-catch
              try {
                  annotationDetector();                
              }
              catch (Exception e) {
                  // ignore
              }
          }

      }

  }
}

3. 引入注解抓取工具包

<!-- 注解抓取工具包 -->
<dependency>
  <groupId>org.reflections</groupId>
  <artifactId>reflections</artifactId>
  <version>0.9.11</version>
</dependency>

4. 处理注解

private void annotationDetector() {

    //扫描方法注解和类注解(可以添加其他类型的注解)
    ConfigurationBuilder builder = new ConfigurationBuilder().useParallelExecutor()
            .setUrls(ClasspathHelper.forClassLoader())
            .setScanners(new MethodAnnotationsScanner(), new TypeAnnotationsScanner());

    Reflections reflections = new Reflections(builder);
    Set<Method> methods = reflections.getMethodsAnnotatedWith(自定义注解类.class);

    for (Method method : methods) {
        annotationFilter(method);
    }
}

private void annotationFilter(Method method) {

    Class<?> declaringClass = method.getDeclaringClass();
    String className = declaringClass.getName();
    String methodName = method.getName();

    Annotation[] methodAnnotations = method.getAnnotations();

    for (Annotation annotation : methodAnnotations) {
        if (annotation.annotationType().equals(自定义注解类.class)) {
            // 对自定义注解进行解析
        }
    }
}

扩展阅读

1. Spring boot中使用aop详解

https://www.cnblogs.com/bigben0123/p/7779357.html

2. 用Spring Aop方式拦截自定义注解的实现

http://blog.csdn.net/bazhuayu_1203/article/details/79399846

3. SpringBoot构建微服务实战 之 @Enable*

https://blog.csdn.net/u012437781/article/details/78625743