阅读(2945) (0)

弹簧教程 - 弹簧汽车线束

2017-01-09 19:06:19 更新

弹簧教程 - 弹簧汽车线束


春天可以自动地蚕豆。要启用它,请在< bean>中定义“autowire"属性。

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="byName" />

弹簧有五种自动接线模式。

  • no - Default, no auto wiring
  • byName - Auto wiring by property name.
  • byType - Auto wiring by property data type.
  • constructor - byType mode in constructor argument.
  • autodetect - If a default constructor is found, use "autowired by constructor"; Otherwise, use "autowire by type".


Java Bean

客户Java bean。

package com.www.zijiebao.common;
public class Customer 
{
  private Person person;
  public Customer(Person person) {
    this.person = person;
  }
  public void setPerson(Person person) {
    this.person = person;
  }
}

Person Java bean

package com.www.zijiebao.common;
public class Person 
{
}


自动接线“否"

这是默认模式,我们需要通过“ref"属性连接Java bean。

<bean id="customer" class="com.www.zijiebao.common.Customer">
         <property name="person" ref="person" />
</bean>
<bean id="person" class="com.www.zijiebao.common.Person" />

自动接线“byName"

以下代码将autowire byName添加到bean声明中。

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="byName" />

因为“person"bean的名称与“customer"bean的名称相同“person"属性,Spring将通过setPerson(Person person)方法自动连接。

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="byName" />
<bean id="person" class="com.www.zijiebao.common.Person" />

自动布线“byType"

以下xml配置将自动连线类型声明为byType。

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="byType" />

因为“person"bean的数据类型与数据类型相同“客户"bean的属性person对象,Spring将通过方法setPerson(Person person)自动连接它。

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="byType" />
<bean id="person" class="com.www.zijiebao.common.Person" />

自动布线“构造函数"

以下代码将bean的自动连线类型声明为构造函数

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="constructor" />

“person"bean的数据类型与“customer"bean的属性(Person对象)中的构造函数参数数据类型相同,Spring将通过构造方法 - “public Customer(Person person)"自动连接它。

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="constructor" />
<bean id="person" class="com.www.zijiebao.common.Person" />

自动布线“构造函数"...

以下代码显示如何使用autodetect autowire。如果找到构造函数,则使用“constructor"; 否则,使用“byType"。

<bean id="customer" class="com.www.zijiebao.common.Customer" 
      autowire="autodetect" dependency-check="objects />

由于在“Customer"类中有一个构造函数,Spring将通过构造方法 - “public Customer(Person person)"自动连接它。

<bean id="customer" class="com.www.zijiebao.common.Customer" autowire="autodetect" />
<bean id="person" class="com.www.zijiebao.common.Person" />