【Spring boot读书笔记】Spring注解编程模型

一、元注解

元注解是指一个能声明在其他注解上的注解,如果一个注解标注在其他注解上,那么它就是元注解。例如

  • @Documented
  • @Inherited
  • @Repeatable (java 8)
  • @Component ( Spring)

二、Spring模式注解

管理和存储某种领域对象的注解,Spring核心部分提供了几种模式注解:

  • @Component
  • @Service
  • @Controller
  • @RestController
  • @Configuration
    Java语言规范,Annotation不允许集成,没有派生子类的negligible,因此Spring采用元注解方式实现注解的派生。

以@RestController为例:

@Component @Service @RestController 派生 派生 @Component @Service @RestController
自定义派生注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // 测试多层次 @Component派生,请将当前注释
public @interface StringRepository {

    /**
     * 属性方法必须与 {@link Component#value()} 保持一致
     * @return Bean 的名称
     */
    String value() default "";
}

@StringRepository("chineseNameRepository")
public class NameRepository {

    /**
     * 查找所有的名字
     *
     * @return non-null List
     */
    public List<String> findAll() {
        return Arrays.asList("张三", "李四", "小马哥");
    }
}


public class DerivedComponentAnnotationBootstrap {

    static {
        // 解决 Spring 2.5.x 不兼容 Java 8 的问题
        // 同时,请注意 Java Security 策略,必须具备 PropertyPermission
        System.setProperty("java.version", "1.7.0");
    }

    public static void main(String[] args) {
        // 构建 XML 配置驱动 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("nameRepository.findAll() = %s \n", nameRepository.findAll());
    }
}

三、派生注解的原理

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值