当前位置: 移动技术网 > IT编程>开发语言>Java > Java注解机制之Spring自动装配实现原理详解

Java注解机制之Spring自动装配实现原理详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

 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自动装配是通过反射机制来实现的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网