spring注解

注解 Annotation

注解,也叫元数据。一种代码级别的说明。它是jdk1.5以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明、注释。
简单来说注解就是代码中的特殊标记,这些标记可以在编译、类加载、运行时被读取,并执行相对应的处理。

注解 编程思想

注解就是个接口,可以放在包、类、字段、方法、局部变量、方法参数等前面,就是一个标签,可以指定存到什么时候的tag,声明式编程,把一系列的操作命令封装成一个标签来简化业务逻辑

JDK内置注解
  • Override:用来告诉编译器要检查该方法是实现父类的方法
  • SuppressWarnings:用来消除一些警告信息,使用集合的时候,如果没有指定泛型,IDE会提示安全检查的警告
  • FunctionalInterface:是JDK8中的注解,用来指定该接口是函数式接口
Annotation和interface的异同
  1. Annotation的类型使用关键字@interface,继承了java.lang.annotation.Annotation接口,并非声明了一个interface
  2. Annotation类型、方法定义是独特的、受限制的。Annotation类型的方法必须申明为无参数、无异常抛出的。这些方法定义了Annotation的成员:方法名称为了成员名,而方法返回值成为了成员的类型。
  3. Annotation类型跟接口一样可以定义常量、静态成员类型、可以被实现或继承
元注解 meta-annotation

元注解的作用就是负责注解其他注解。jdk1.5定义了四个标准的meta-annotation类型,他们被用力啊提供对其他Annotation类型作说明

  1. @Target
  2. @Retention
  3. @Document
  4. @Inherited
@Target

@Target说明了Annotation所修饰的对象范围:Annotation可被用于packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了Target可更加明晰其修饰的目标
作用:用于描述注解的使用范围
取值(ElementType)有:

  1. CONSTRUCTOR:用户描述构造器
  2. FIELD:用于描述域
  3. LOCAL_VARIABLE:用于描述局部变量
  4. METHOD:用于描述方法
  5. PACKAGE:用于描述包
  6. PARAMETER:用于描述参数
  7. TYPE:用于描述类、接口(包括注解类型) 或enum声明
Retention

Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。
作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期
取值(RetentionPoicy)有:

  1. SOURCE:在源文件中有效(即源文件保留)
  2. CLASS:在class文件中有效(即class保留)
  3. RUNTIME:在运行时有效(即运行时保留)
    当注解的RetentionPolicy的属性值是RUTIME,这样注解处理器可以通过反射,获取到该注解的属性值,从而去做一些运行时的逻辑处理
Documented:

@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
@Inherited:
  @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
  注意:@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。
  当@Inherited annotation类型标注的annotation的Retention是RetentionPolicy.RUNTIME,则反射API增强了这种继承性。如果我们使用java.lang.reflect去查询一个@Inherited annotation类型的annotation时,反射代码检查将展开工作:检查class和其父类,直到发现指定的annotation类型被发现,或者到达类继承结构的顶层。

@Autowired注解解析

启动注解的自动注入

<context:annotation-config />

首先看看 <context:annotation-config />的定义

<xsd:element name="annotation-config">
		<xsd:annotation>
			<xsd:documentation><![CDATA[
	Activates various annotations to be detected in bean classes: Spring's @Required and
	@Autowired, as well as JSR 250's @PostConstruct, @PreDestroy and @Resource (if available),
	JAX-WS's @WebServiceRef (if available), EJB 3's @EJB (if available), and JPA's
	@PersistenceContext and @PersistenceUnit (if available). Alternatively, you may
	choose to activate the individual BeanPostProcessors for those annotations.

	Note: This tag does not activate processing of Spring's @Transactional or EJB 3's
	@TransactionAttribute annotation. Consider the use of the <tx:annotation-driven>
	tag for that purpose.

	See javadoc for org.springframework.context.annotation.AnnotationConfigApplicationContext
	for information on code-based alternatives to bootstrapping annotation-driven support.
			]]></xsd:documentation>
		</xsd:annotation>
	</xsd:element>

可以看出:类内部的注解,如@Autowired、@Value、@Required、@Resource以及EJB和WebService相关的注解,是容器对Bean对象实例化和依赖注入时,通过容器中注册的Bean后置处理器AnnotationConfigApplicationContext处理这些注解的。
所以配置了上面这个配置(context:component-scan(开启扫描包)假如有配置这个,那么就可以省略<context:annotation-config />)后,将隐式地向Spring容器注册AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor以及这4个专门用于处理注解的Bean后置处理器。
当 Spring 容器启动时,AutowiredAnnotationBeanPostProcessor 将扫描 Spring 容器中所有 Bean,当发现 Bean 中拥有@Autowired 注解时就找到和其匹配(默认按类型匹配)的 Bean,并注入到对应的地方中去。
通过org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor可以实现依赖自动注入

Spring 是如何通过@AutoWired 自动注入 Bean 属性和 Map,List 集合的?

Spring按类型自动装配注入数组、集合、Map时,是把应用上下文中对应类型的bean装配进集合,而不是直接查找一个对应类型的集合然后注入

  1. 如果是数组,则获取数组元素类型,查找匹配该类型的所有bean,返回一个这些bean的数组;
  2. 如果该类可赋给Collection,并且是一个接口,则获取集合元素类型,查找匹配该类型的所有bean,返回一个这些bean的集合;
  3. 如果该类型是Map(注意是type == Map.class),且key是String类型,则获取Map的value的类型,查找匹配该类型的所有bean,这是一个key为bean name、value为bean实例的一个Map,返回这个Map。
  4. 其他情况则是我们所熟知的按类型自动装配过程。
自定义注解

使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数方法的名称就是参数的名称,返回值类型就是参数的类型
(返回值类型只能是基本类型、Class、String、enum)包装类不可以!!!。可以通过default来声明参数的默认值。

package com.example.demo.Annotation;
import java.lang.annotation.*;
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnoation {
     String name() default "我是默认值";
}

参数即方法名注意事项:

  1. 只能用public或默认(default)这两个访问权修饰.例如,String value();
  2. 参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和 String,Enum,Class,annotations等数据类型,以及这一些类型的数组
  3. 如果只有一个参数成员,最好把参数名称设为"value"
@Aspect
@Component
public class AnnotationAspect {

    @Pointcut("@annotation(com.example.demo.Annotation.CustomAnnoation)")
    public void cut(){};

    @Before("cut()")
    public void before(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation:annotations){
            System.out.println("~~~"+annotation.annotationType());
        }
        // 是否包含自定义注解
        if (method.isAnnotationPresent(CustomAnnoation.class)){
            // 获得注解
            CustomAnnoation annotation = method.getAnnotation(CustomAnnoation.class);
            // 调用注解的内容
            System.out.println("注解内容:"+annotation.name());
        }
    }
}
@CustomAnnoation(name = "砥砺前行")
@RequestMapping("/annotation")
public String huwq() {
    return "QQQ";
}
输出
~~~interface com.example.demo.Annotation.CustomAnnoation
~~~interface org.springframework.web.bind.annotation.RequestMapping
注解内容:砥砺前行

如果是Field注解则是先获取对象class对象

Class targetClass = arg.getClass();
        TableName annotation = (TableName) targetClass.getAnnotation(TableName.class);
        tableName = annotation.value();

其他例子不再赘述。。

后续目标

  1. 为何能够直接使用@Autowired进行依赖注入?是如何工作的?
  2. Spring 是如何通过@AutoWired 自动注入 Bean 属性和 Map,List 集合的?
  3. @Required 是如何起到检查xml里面属性有没有被配置的?
  4. Spring 框架是如何把标注@Component 的 Bean 注入到容器?
  5. @Configuration,@ComponentScan,@Import,@Bean 注解是是如何工作的?
  6. 使用@PropertySource 引入配置文件,那么配置文件里面的配置是如何被注册到 Spring 环境里面的?
  7. 讲解如何通过自定义注解实现一个简单的树形文档生成?

参考
Spring5源码解析-@Autowired

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值