自动装配Bean属性
自动装配的4种类型
ByName 把与bean的属性具有相同名字(或者id)的其他bean自动装配到该bean的属性中。
ByType 把与bean的属性具有相同类型的其他bean自动装配到该bean的属性中。
constructor 把与bean的构造方法中参数相同类型的bean自动装配到对应参数中。
autodetect 自动选择装配类型
通过指定配置文件中bean标签的autowire属性为相应类型,既可实现配置文件方式的自动装配。
通过指定beans标签的default-autowire属性可以配置,所有bean的默认自动装配方式。
我更偏向于使用注解方式实现自动装配,因此上面这种方式就不多讲了。
使用注解装配
使用注解装配前需要在配置文件中开启,可以添加如下配置开启。
<context:annotation-config/>
Spring3支持几种注解:@Autowired,@Inject,@Resource
@Autowired注解
这是Spring自带的注解,可以注解属性,方法以及构造方法等,采取的策略是ByType。
值得一提的是它甚至可以注解私有属性且属性没有set方法。
@Autowired注解有个required参数,可以指定如果没有找到可匹配bean的行为,比如将@Autowired(required=false)在找不到bean后就会将属性设置为Null。
下面代码使用它注解了set方法。
public class PerformerImpl implements Performer{
private String name;
private String sex;
private ISong song;
private List<Person> parent;
public PerformerImpl(String name,ISong song){
this.name=name;
this.song=song;
}
public void setName(String name){
this.name=name;
}
public void setSex(String sex){
this.sex=sex;
}
@Autowired
public void setParent(List<Person> parent){
this.parent=parent;
}
public void perform() {
System.out.println("演唱者:"+name);
System.out.println("性别:"+sex);
System.out.println("歌曲信息:");
this.song.info();
System.out.println("家庭信息:");
for (Person p : parent) {
p.info();
}
}
}
配置文件:
<bean id="f" class="bean.Person">
<property name="name" value="lu XX" />
</bean>
<bean id="m" class="bean.Person">
<property name="name" value="wang XX" />
</bean>
<bean id="performImpl" class="bean.PerformerImpl" scope="prototype">
<constructor-arg value="yukjin" />
<constructor-arg ref="song" />
<property name="sex" value="male" />
</bean>
可以看到不需要在performImpl中手动注入parent属性了。