我是靠谱客的博主 眼睛大乌龟,最近开发中收集的这篇文章主要介绍Spring的自动装配,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Spring的自动装配

    自动装配的形式有byType、byName、no、construtor、autodetect和default(beans标签中没有,而bean标签中有该属性),共6种装配的方式。

    byType:在容器中寻找一个与需要自动装配的属性类型相同的Bean,如没有找到相符Bean,该属性就没有被装配上,如果找到超过一个相符的Bean时(不能出现有继承的两个类),会抛出No unique bean of type的异常

Xml中的部分代码:

<!-- 设置addressserviceimpl类 -->

<bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl">

<property name="address">

<value>河北邢台</value>

</property>

</bean>

<!-- 设置emp类的属性 -->

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"

autowire="byType">

</bean>

    byName:在容器中寻找和需要自动装配的属性名相同的Bean(或ID),如果没有找到相符的Bean,该属性就没有被装配上。

Xml中的部分代码:

<!-- 设置addressserviceimpl类 -->

<bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl">

<property name="address">

<value>河北邢台</value>

</property>

</bean>

<!-- 设置emp类的属性 -->

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl"

autowire="byName">

</bean>

<!-- 设置hour的属性  -->

<bean id="hourServiceImpl" class="cn.csdn.service.HourServiceImpl">

</bean>

    注意:byName和byType使用前要有一个默认的构造器,必须保证Bean能够初始化,否则的话会出现

constructor:在容器中寻找与需要自动装配的Bean的构造方法参数一致的一个或多个Bean。如存在不确定Bean或构造方法,容器会抛出org.springframework.bean.unisatisfiedBependencyException异常。通过构造器注入的,构造器中的参数是按照byType装配的

Xml中的部分代码:

<!-- 设置addressserviceimpl类 -->

<bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl">

<property name="address">

<value>河北邢台</value>

</property>

</bean>

<!-- 设置emp类的属性 -->

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl2"

autowire="constructor">

</bean>

    no:不自动装配,必须让用户自己装配,装配时用到ref的属性。这种方式是默认的装配方式

autodetect:测试Autodetect自动装配的方法,如果没有默认的构造方法时调用seter方法,seter方法也没有的话,就不能操作了;如果有默认的构造方法,先调用默认的构造方法,如果有seter方法的话,再调用seter方法,如果没有的话,只调用默认的构造方法

Xml中的部分代码:

<!-- 设置addressserviceimpl类 -->

<bean id="addressServiceImpl" class="cn.csdn.service.AddressServiceImpl">

<property name="address">

<value>河北邢台</value>

</property>

</bean>

<!-- 设置emp类的属性 -->

<bean id="empServiceImpl" class="cn.csdn.service.EmpServiceImpl3"

autowire="autodetect">

</bean>

    default:这种装配方式只有bean标签有这个属性,相当于beans标签中的default-autowire="no"

源码已经上传,欢迎下载!

 

最后

以上就是眼睛大乌龟为你收集整理的Spring的自动装配的全部内容,希望文章能够帮你解决Spring的自动装配所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(102)

评论列表共有 0 条评论

立即
投稿
返回
顶部