您现在的位置是:首页 > 文章详情

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

日期:2018-11-29点击:491

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


本文出自:https://blog.yoodb.com/yoodb/article/detail/1310

原文链接:https://blog.roncoo.com/article/130546
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章