代码验证Spring注解的派生性

469 阅读1分钟

一 前言

前面的文章有说Spring注解是没有继承一说的,那么注解想要其他注解的功能怎么办,这就要用到spring注解的派生性,下面就通过代码来进行验证。

二 代码验证

  1. 写一个自定义注解StringResposity

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface StringResposity {
        /**
         * 属性方法名称必须与{@link Component#value()}保持一致
         * @return bean 的名称
         */
        String value() default "";
    
    }
    
  2. 将注解标记在类上

    @StringResposity("chineseNameRepository")
    public class NameRepository {
        /**
         * 查找所有的名字
         * @return
         */
        public List<String> findAll(){
    
            return Arrays.asList("allen","json","diva");
        };
    }
    
  3. 编写配置文件,加载配置文件时扫描类

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
       
    
        <!-- 找寻被@Component或者其派生 Annotation 标记的类(Class),将它们注册为 Spring Bean -->
        <context:component-scan base-package="com.example.demo.annotation" />
    
    </beans>
    
  4. 验证

    public class DerivedComponentAnnotationBootStrap {
      
    
        public static void main(String[] args) {
            // 构建spring上下文
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
            // 设置xml的文件地址
            context.setConfigLocation("classpath:/META-INF/spring/context.xml");
            // 启动上下文
            context.refresh();
            // 获取文件名为chineseNameRepository 的bean对象
            NameRepository nameRepository = (NameRepository)context.getBean("chineseNameRepository");
            // 输出用户名
            System.out.printf("nameRespority.findAll() = %s \n",nameRepository.findAll());
        }
    }
    

    如过这里输出了"allen","json","diva"证明类被扫描到了容器,@StringResposity拥有了@Component的功能,证明存在注解的派生性 执行下,执行结果为

    nameRespority.findAll() = [allen, json, diva] 说明spring存在注解的派生性