什么是bean的自动装配,有哪些方式? -- java面试
自动装配与手动装配
Spring自动装配:无需在Spring配置文件中描述javaBean之间的依赖关系(如配置<property>
、<constructor-arg>
)。 IOC容器会自动建立javaBean之间的关联关系。
如果没有采用自动装配的话,就需要手动装配,通常在配置文件中实现。
以下代码就是手动装配:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="customerDAO" class="com.hebeu.customer.dao.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
通过<property name="dataSource" ref="dataSource" />
向customerDAO的bean注入了dataSource。
在Spring框架中,只需要在中定义"autowire"属性,即可开启自动装配功能。
<bean id="customer" class="com.yiibai.common.Customer" autowire="byName" />
自动装配模式
在Spring中,支持5种自动装配模式。
-
no 缺省情况下,自动配置是通过"ref"属性手动设定
-
byName 根据bean的属性名称进行自动装配
Cutomer的属性名称是person,Spring会将bean id为person的bean通过setter方法进行自动装配。
<bean id="cutomer" class="com.xxx.xxx.Cutomer" autowire="byName"/>
<bean id="person" class="com.xxx.xxx.Person"/>
-
byType 根据bean的类型进行自动装配
Cutomer的属性person的类型为Person,Spirng会将Person类型通过setter方法进行自动装配。
<bean id="cutomer" class="com.xxx.xxx.Cutomer" autowire="byType"/>
<bean id="person" class="com.xxx.xxx.Person"/>
-
constructor 类似byType,不是是应用于构造器的参数。如果一个bean与构造器参数的类型相同,则进行自动装配,否则导致异常。
Cutomer构造函数的参数person的类型为Person,Spirng会将Person类型通过构造方法进行自动装配。
<bean id="cutomer" class="com.xxx.xxx.Cutomer" autowire="construtor"/> <bean id="person" class="com.xxx.xxx.Person"/>
-
autodetect 如果有默认的构造器,则通过constructor方式自动装配,否则使用byType方式自动装配。
在Spring3.0以后的版本被废弃,已经不再合法了。