温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java注解机制之Spring自动装配实现原理的示例分析

发布时间:2021-07-28 09:10:50 来源:亿速云 阅读:115 作者:小新 栏目:编程语言

小编给大家分享一下Java注解机制之Spring自动装配实现原理的示例分析,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

 Java中使用注解的情况主要在SpringMVC(Spring Boot等),注解实际上相当于一种标记语言,它允许你在运行时动态地对拥有该标记的成员进行操作。注意:spring框架默认不支持自动装配的,要想使用自动装配需要修改spring配置文件中<bean>标签的autowire属性。

自动装配属性有6个值可选,分别代表不同的含义:

byName ->从Spring环境中获取目标对象时,目标对象中的属性会根据名称在整个Spring环境中查找<bean>标签的id属性值。如果有相同的,那么获取这个对象,实现关联。整个Spring环境:表示所有的spring配置文件中查找,那么id不能有重复的。 

byType ->从Spring环境中获取目标对象时,目标对象中的属性会根据类型在整个spring环境中查找<bean>标签的class属性值。如果有相同的,那么获取这个对象,实现关联。

缺点:如果存在多个相同类型的bean对象,会出错;如果属性为单一类型的数据,那么查找到多个关联对象会发生错误;如果属性为数组或集合(泛型)类型,那么查找到多个关联对象不会发生异常。

constructor ->使用构造方法完成对象注入,其实也是根据构造方法的参数类型进行对象查找,相当于采用byType的方式。

autodetect ->自动选择:如果对象没有无参数的构造方法,那么自动选择constructor的自动装配方式进行构造注入。如果对象含有无参数的构造方法,那么自动选择byType的自动装配方式进行setter注入。                     

no ->不支持自动装配功能

default ->表示默认采用上一级标签的自动装配的取值。如果存在多个配置文件的话,那么每一个配置文件的自动装配方式都是独立的。

注解使用需要三个条件包括注解声明,使用注解的元素,操作使用注解元素的代码。第一步注解声明,注解是一种类型,自定义注解编写代码如下:

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AttachAnnotation {
  String paramValue() default "河北省"; // 参数名为"paramValue" 默认值为"河北省"
}

使用自定义注解元素,代码如下:

package annotation;

/**
 * @author 路人宅
 */
public class AttachEmlement {

  // 普通
  public void AttachDefault(String name){
    System.out.println("归属:" + name);
  }
  
  // 使用注解并传入参数
  @AttachAnnotation(paramValue="河北省")
  public void AttachAnnotation(String name){
    System.out.println("归属:" + name);
  }
  
  // 使用注解并使用默认参数
  @AttachAnnotation
  public void AttachAnnotationDefault(String name){
    System.out.println("归属:" + name);
  }
}

测试操作执行main函数,具体代码如下:

package annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AnnotionOperator {
 public static void main(String[] args) throws IllegalAccessException,
  IllegalArgumentException, InvocationTargetException,
  ClassNotFoundException {
 AttachEmlement element = new AttachEmlement(); // 初始化一个实例,用于方法调用
 Method[] methods = AttachEmlement.class.getDeclaredMethods(); // 获得所有方法

 for (Method method : methods) {
  AttachAnnotation annotationTmp = null;
  if ((annotationTmp = method.getAnnotation(AttachAnnotation.class)) != null)
  method.invoke(element, annotationTmp.paramValue());
  else
  method.invoke(element, "河南省");
 }
 }
}

执行结果:

归属: 河南省
归属:河北省
归属:河北省

Spring为了方便自动装配进行操作有两种方式:继承org.springframework.web.context.support.SpringBeanAutowiringSupport类或者添加@Component/@Controller等注解并在Spring配置文件里声明context:component-scan元素配置。

1) 继承方式实现自动装配,查看Spring3.1.1源代码会发现SpringBeanAutowiringSupport类中有如下代码:

/**
 * This constructor performs injection on this instance,
 * based on the current web application context.
 * Intended for use as a base class.
 * @see #processInjectionBasedOnCurrentContext
 */
public SpringBeanAutowiringSupport() {
 processInjectionBasedOnCurrentContext(this);
}

分析:Java在实例化构造时会调用默认父类无参构造方法,而Spring就是通过这一点,让操作元素代码执行的。

2) 通过注解方式的也和上述理论相似,值得注意的是注解自动装配无需完成注入setter*,查看Spring3.1.1源码注解调用顺序得出:
org.springframework.web.context.support.SpringBeanAutowiringSupport#SpringBeanAutowiringSupport=>
org.springframework.web.context.support.SpringBeanAutowiringSupport#processInjectionBasedOnCurrentContext=>
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#processInjection=>
org.springframework.beans.factory.annotation.InjectionMetadata#Injection,查看inject方法源代码如下:

/**
 * Either this or {@link #getResourceToInject} needs to be overridden.
 */
protected void inject(Object target, String requestingBeanName, PropertyValues pvs) throws Throwable {
 if (this.isField) {
 Field field = (Field) this.member;
 ReflectionUtils.makeAccessible(field);
 field.set(target, getResourceToInject(target, requestingBeanName));
 }
 else {
 if (checkPropertySkipping(pvs)) {
  return;
 }
 try {
  Method method = (Method) this.member;
  ReflectionUtils.makeAccessible(method);
  method.invoke(target, getResourceToInject(target, requestingBeanName));
 }
 catch (InvocationTargetException ex) {
  throw ex.getTargetException();
 }
 }
}

分析:通过上述源码Spring自动装配是通过反射机制来实现的。

看完了这篇文章,相信你对“Java注解机制之Spring自动装配实现原理的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI