文章目录
  1. 1. Spring自动注入模型
    1. 1.1. byName
    2. 1.2. byType
    3. 1.3. constructor
    4. 1.4. autodetect

Spring自动注入模型

  • No(Spring 默认模式)

    Bean引用需通过 来指明

  • byName
  • byType

    如果找到多个符合条件,抛出异常;如果没有找到,该属性值不会被设置。

  • constructor

    和 byType 类似,应用在构造参数;如果没有找到,报错。

  • auotdetect

    通过对 Bean 的内省来选择 constructor 或者 byType。

    1. 是否有带参构造函数,如果有,采用 constructor 模式;否则2.
    2. 只有默认构造函数,将采用 byType。

byName

autowire=”byName”

1
2
3
4
5
6
7
8
<bean id="employee" class="com.loogeoustc.beans.EmployeeBean" autowire="byName">
<property name="fullName" value="loogeoustc"/>
</bean>
<bean id="departmentBean" class="com.loogeoustc.beans.DepartmentBean" >
<property name="name" value="Human Resource" />
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class EmployeeBean
{
private String fullName;
private DepartmentBean departmentBean;
//setter and getter Methods
}
public class DepartmentBean {
private String name;
//setter and getter Methods
}

byType

autowire=”byType”

  1. 加入注解支持
  2. 使用 @Autowired
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!--1. 加入注解支持-->
<!--1.a 法1-->
<context:annotation-config />
<!--1.b 法2-->
<bean class ="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="employee" class="com.loogeoustc.byType.EmployeeBean" autowire="byType">
<property name="fullName" value="Lokesh Gupta"/>
</bean>
<bean id="department" class="com.loogeoustc.DepartmentBean" >
<property name="name" value="Human Resource" />
</bean>
1
2
3
4
5
6
7
8
9
10
public class EmployeeBean
{
@Autowired
private DepartmentBean departmentBean;
private String fullName;
//setter and getter Methods
}

constructor

autowire=”constructor”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<context:annotation-config />
<!--法1:使用 autowire="constructor"-->
<bean id="employee" class="com.loogeoustc.EmployeeBean" autowire="constructor">
<property name="fullName" value="Lokesh Gupta"/>
</bean>
<!--法2 不使用 autowire="constructor"-->
<bean id="employee" class="com.loogeoustc.EmployeeBean">
<property name="fullName" value="Lokesh Gupta"/>
<constructor-arg>
<ref bean="department" />
</constructor-arg>
</bean>
<bean id="department" class="com.loogeoustc.DepartmentBean" >
<property name="name" value="Human Resource" />
</bean>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class EmployeeBean
{
private String fullName;
private DepartmentBean departmentBean;
public EmployeeBean(DepartmentBean departmentBean)
{
this.departmentBean = departmentBean;
}
//setter and getter Methods
}

autodetect

autowire=”autodetect”

1
2
3
4
5
6
7
8
<bean id="employee" class="com.loogeoustc.EmployeeBean" autowire="autodetect">
<property name="fullName" value="Lokesh Gupta"/>
</bean>
<bean id="department" class="com.loogeoustc.DepartmentBean" >
<property name="name" value="Human Resource" />
</bean>
文章目录
  1. 1. Spring自动注入模型
    1. 1.1. byName
    2. 1.2. byType
    3. 1.3. constructor
    4. 1.4. autodetect