登录  /  注册
首页 > Java > java教程 > 正文

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

黄舟
发布: 2017-10-18 10:06:16
原创
2104人浏览过

这篇文章主要为大家详细介绍了java注解机制之spring自动装配实现原理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

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

byType ->从Spring环境中获取目标对象时,目标对象中的属性会根据类型在整个spring环境中查找标签的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自动装配原理的详解的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号