基于@AliasFor注解的用法及说明

 更新时间:2023年02月27日 14:56:53   作者:怪 咖@  
这篇文章主要介绍了基于@AliasFor注解的用法及说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

一、前言

@AliasFor注解基本上都是在spring源码当中出现的,AliasFor是Spring提供的注解,Alias是别名的意思,For是为了,首先我们通过命名可以得出一个结论,他是为了别名而自定义的注解!

Spring中@AliasFor注解的作用有两点:

  • 将同一个注解类的属性设置互为别名
  • 将一个注解上的属性值传递给另一个注解

但这并不是java原生支持的,需要通过Spring中提供的工具类:org.springframework.core.annotation.AnnotationUtils或者org.springframework.core.annotation.AnnotatedElementUtils来解析。AnnotatedElementUtils内部还是调用的AnnotationUtils。

源码如下:它有三个属性value和attribute以及annotation,@AliasFor注解注释了自身,并且value和attribute互为别名,通过源码很容易知道,当我们使用这个注解,@AliasFor(value=“xxx”)@AliasFor(attribute=“xxx”)是等价的。

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Documented
public @interface AliasFor {
    @AliasFor("attribute")
    String value() default "";

    @AliasFor("value")
    String attribute() default "";

    Class<? extends Annotation> annotation() default Annotation.class;
}

二、AnnotationUtils 和 AnnotatedElementUtils

Java 运行时读取Annotation 需要通过反射,Spring 提供AnnotationUtils , AnnotationElementUtils 用于简化操作,其他特点如下:

  • 查询Meta Annotation(注解的注解)
  • 对@AliasFor 解析,生成指定注解的代理,并赋值。(注:定义其他Annotation 的别名)

Utils 调用涉及的元素:

  • Annotation: Annotation 元数据
  • AnnotatedElement: 被Annotation注解的对象,包括annotation , class , method等
  • Method: 类和接口中的方法信息

AnnotationUtils常用方法:

  • getAnnotation: 从某个类获取某个annotation
  • findAnnotation: 从类或方法中查找某个annotation。
  • isAnnotationDeclaredLocally: 验证annotation是否直接注释在类上而不是集成来的。
  • isAnnotationInherited: 验证annotation是否继承于另一个class。
  • getAnnotationAttributes: 获取annotation的所有属性。
  • getValue: 获取指定annotation的值.
  • getDefaultValue: 获取指定annotation或annotation 属性的默认值

AnnotatedElementUtils常用方法:

findMergedAnnotation:这个方法会合并@AliasFor传递的值

三、同一个注解类的属性设置互为别名

1.自定义一个EnableCVS 注解

一共有两个属性

import org.springframework.core.annotation.AliasFor;

import java.lang.annotation.*;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EnableCVS {
	
	// 这里就算是改成@AliasFor(attribute = "address")测试结果也是一样的
    @AliasFor(value = "address")
    String value() default "";

    @AliasFor(value = "value")
    String address() default "";
}

2.创建一个类

然后使用自定义的注解@EnableCVS修饰

@Configuration
@EnableCVS(address = "hhh")
public class AppConfig {

}

3.测试:通过两种方式获取自定义注解当中的属性值

import org.springframework.core.annotation.AnnotationUtils;

public class Test {
    public static void main(String[] args) {
    	// spring提供的
        EnableCVS annotation = AnnotationUtils.findAnnotation(AppConfig.class, EnableCVS.class);
        System.out.println("AnnotationUtils:address:" + annotation.address());
        System.out.println("AnnotationUtils:value:" + annotation.value());
		
		// jdk原生
        EnableCVS annotation1 = AppConfig.class.getAnnotation(EnableCVS.class);
        System.out.println("AppConfig:address:" + annotation1.address());
        System.out.println("AppConfig:value:" + annotation1.value());
    }
}

4.输出结果如下

首先我们设置的注解是@EnableCVS(address = "hhh") ,只设置了address属性,并没有设置value属性,会发现jdk原生方式获取value的时候是拿不到值的,而spring提供的AnnotationUtils却可以获取到,而且获取到的就是address的值!

其实就可以理解为,一旦value值设置了如下注解@AliasFor(value = "address"),也就意味着通过AnnotationUtils来获取value属性值的时候,当value值没有设置的时候,实际上会去获取address属性的值!

@AliasFor(value = "address")
String value() default "";

注意:如果@AliasFor注解当中两个属性互相设置了@AliasFor别名,并且使用自定义注解的时候,同时设置address和value的值,这时候通过AnnotationUtils#findAnnotation(Class<?>, annotationType)获取属性值,则会抛出异常!

示例如下:

@Configuration
@EnableCVS(value = "hhh",address = "222")
public class AppConfig {

}

四、将一个注解上的属性值传递给另一个注解

1.自定义注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Scope("singleton")
@Component
@Inherited
public @interface SingletonComponent {

    @AliasFor(annotation = Component.class, attribute = "value")
    String value() default "";
}

2.声明一个类

使用@SingletonComponent修饰

@SingletonComponent("simpleService")
public class SimpleSingletonService {

}

3.通过AnnotationUtils和AnnotatedElementUtils获取注解

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

// 这个注解一定要加,不然getAllAnnocations方法获取不到值
@ComponentScan
public class AnnotationUtilsDemo {
    private static void annotationUtilsDemo() {

        // 获取类注解
        SingletonComponent singletonComponentAnnocation = AnnotationUtils.
                findAnnotation(SimpleSingletonService.class, SingletonComponent.class);

        System.out.println("@SingletonComponent : " + singletonComponentAnnocation);
        System.out.println("@SingletonComponent value: " + AnnotationUtils.getValue(singletonComponentAnnocation, "value"));


        System.out.println("----------------------------------------------");

        Scope scopeAnnocation = AnnotationUtils.findAnnotation(SimpleSingletonService.class, Scope.class);
        System.out.println("@Scope : " + scopeAnnocation);
        System.out.println("@Scope value: " + AnnotationUtils.getValue(scopeAnnocation, "scopeName"));

        System.out.println("----------------------------------------------");

        // 获取@AliasFor Marge 后的注解,直接调用 AnnotationUtils的方法不会组合@AliasFor的值,需要调用AnnotatedElementUtils
        Component componentAnnocation = AnnotatedElementUtils.findMergedAnnotation(SimpleSingletonService.class, Component.class);
        System.out.println("@Component : " + componentAnnocation);
        System.out.println("@Component value: " + AnnotationUtils.getValue(componentAnnocation, "value"));
    }

    private static void getAllAnnocations() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnotationUtilsDemo.class);
        // 获取SingletonComponent注解修饰的类
        Map<String, Object> beans = context.getBeansWithAnnotation(SingletonComponent.class);
        for (Object bean : beans.values()) {
            System.out.println("bean : " + bean);
            // @SingletonComponent 继承了 @Component 所以存在实例,@Component的value值就是通过@AliasFor注解传递过去的
            Component componentAnnocation = AnnotatedElementUtils.findMergedAnnotation(bean.getClass(), Component.class);
            System.out.println(componentAnnocation);
        }
    }

    public static void main(String[] args) {
        AnnotationUtilsDemo.annotationUtilsDemo();

        System.out.println("----------------------------------------------");

        AnnotationUtilsDemo.getAllAnnocations();
    }
}

4.输出结果

Connected to the target VM, address: '127.0.0.1:49763', transport: 'socket'
@SingletonComponent : @com.gzl.cn.springbootnacos.aa.SingletonComponent(value="simpleService")
@SingletonComponent value: simpleService
----------------------------------------------
@Scope : @org.springframework.context.annotation.Scope(proxyMode=DEFAULT, scopeName="singleton", value="singleton")
@Scope value: singleton
----------------------------------------------
@Component : @org.springframework.stereotype.Component(value="simpleService")
@Component value: simpleService
----------------------------------------------
bean : com.gzl.cn.springbootnacos.aa.SimpleSingletonService@1b759d6
@org.springframework.stereotype.Component(value="simpleService")

五、@AliasFor注解应用场景

5.1. @SpringBootApplication源码

如下所示@SpringBootApplication并没有定义新的属性,而是复用其他注解已有的注解属性,并对其进行组合形成新的注解从而到达到便捷的目的。

这样的注解我们可以称之为复合注解。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    @AliasFor(annotation = EnableAutoConfiguration.class)
    Class<?>[] exclude() default {};

    @AliasFor(annotation = EnableAutoConfiguration.class)
    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class<?>[] scanBasePackageClasses() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "nameGenerator"
    )
    Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;

    @AliasFor(annotation = Configuration.class)
    boolean proxyBeanMethods() default true;
}

所以在使用SpringBoot 时我们只需要@SpringBootApplication一个注解就能开启自动配置,自动扫描的功能。

而不再需要使下面三个注解来达到同样的目的。

@Configuration
@ComponentSan
@EnnableAutoConfiguration

5.2. @RequestMapping源码

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
    String name() default "";

    @AliasFor("path")
    String[] value() default {};

    @AliasFor("value")
    String[] path() default {};

    RequestMethod[] method() default {};

    String[] params() default {};

    String[] headers() default {};

    String[] consumes() default {};

    String[] produces() default {};
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • 详解记录Java Log的几种方式

    详解记录Java Log的几种方式

    很多小伙伴不知道如何记录日志,今天特地整理了本篇文章,文中有非常详细的介绍及代码示例,对小伙伴们很有帮助,需要的朋友可以参考下
    2021-06-06
  • java8时间 yyyyMMddHHmmss格式转为日期的代码

    java8时间 yyyyMMddHHmmss格式转为日期的代码

    这篇文章主要介绍了java8时间 yyyyMMddHHmmss格式转为日期的代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • Spring整合ehCache全过程

    Spring整合ehCache全过程

    这篇文章主要介绍了Spring整合ehCache全过程,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • MybatisPlus操作符和运算值详解

    MybatisPlus操作符和运算值详解

    在前端到后端的数据传递中,处理动态运算条件是一个常见的需求,本文介绍了如何在MybatisPlus中处理运算符和运算值的动态拼接问题,感兴趣的朋友一起看看吧
    2024-10-10
  • Javamail使用过程中常见问题解决方案

    Javamail使用过程中常见问题解决方案

    这篇文章主要介绍了Javamail使用过程中常见问题解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • Java多线程编程中的并发安全问题及解决方法

    Java多线程编程中的并发安全问题及解决方法

    保障多线程并发安全,解决线程同步与锁竞争问题,提高应用性能与可靠性。多线程编程需要考虑线程安全性,使用同步机制保证共享变量的一致性,避免线程竞争导致的数据不一致与死锁等问题。常用的同步机制包括synchronized、ReentrantLock、volatile等
    2023-04-04
  • Java遍历字符串和统计字符个数的操作方法

    Java遍历字符串和统计字符个数的操作方法

    这篇文章主要介绍了Java遍历字符串和统计字符个数的操作方法,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2024-12-12
  • Java实现鼠标拖放功能的方法

    Java实现鼠标拖放功能的方法

    这篇文章主要介绍了Java实现鼠标拖放功能的方法,很实用的功能,需要的朋友可以参考下
    2014-07-07
  • 区块链常用数据库leveldb用java来实现常规操作的方法

    区块链常用数据库leveldb用java来实现常规操作的方法

    这篇文章主要介绍了区块链常用数据库leveldb用java来实现常规操作,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-02-02
  • Java8通过Function获取字段名的方法(获取实体类的字段名称)

    Java8通过Function获取字段名的方法(获取实体类的字段名称)

    Java8通过Function获取字段名。不用再硬编码,效果类似于mybatis-plus的LambdaQueryWrapper,对Java8通过Function获取字段名相关知识感兴趣的朋友一起看看吧
    2021-09-09

最新评论