Spring IoC容器能够帮助你自动装配Bean。你只要在<bean>的autowire属性中指定自动装配模式就可以了
自动装配的类型
1、no:不执行自动装配,必须显示地装配依赖,为默认
2、byName:根据名称装配
3、byType:根据类型装配
4、Constructor:根据构造程序参数
5、autodetect:如果找到一个没有参数的默认构造函数,依赖将按照类型自动装配
可以在根元素设置default-autowire,因为自动装配由Spring在运行时执行,你无法从Bean配置文件中得到Bean装配的方式,在实践中建议将自动装配用在不复杂的程序中
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<!-- 添加注解功能 -->
<context:annotation-config/>
<!-- 配置一个Bean -->
<bean name="studentBean" class="com.lkt.entity.Student" scope="prototype" autowire="byType" >
<property name="password" value="zhangsan"></property>
<property name="userName" value="zhangsan"></property>
<property name="realName" value="zhangsan"></property>
</bean>
<bean name="classBean" class="com.lkt.entity.Clazz" scope="prototype">
<property name="className" value="一年三班"></property>
</bean>
</beans>
配置文件的自动装配方式不灵活,所有Spring提供了注解的方式来自动装配,即使用@Autowired
在实体类中添加@Autowired,同时Spring运行你指定一个候选的Bean,这个Bean的名称在@Qualifier注解中提供
package com.lkt.entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
public class Student {
private String userName;
private String password;
private String realName;
@Autowired
@Qualifier("classBean")
private Clazz clazz;
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
public Student() {
// TODO Auto-generated constructor stub
}
public Student(String userName,String password,String realName) {
this.userName=userName;
this.password=password;
this.realName=realName;
}
@Override
public String toString() {
return "userName:"+userName+" password:"+password+" realName:"+realName;
}
public String getUserName() {
return userName;
}
@Required
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
@Required
public void setPassword(String password) {
this.password = password;
}
public String getRealName() {
return realName;
}
@Required
public void setRealName(String realName) {
this.realName = realName;
}
}
如果你希望使用按照名称自动装配Bean属性,可以使用@Resource注解设置
@Resource(name="classBean")