set注入要求Bean提供一个默认的构造函数,并为需要注入的属性提供对应的Setter方法。
Spring先调用Bean的默认构造函数实例化Bean对象,然后通过反射的方式调用Setter方法注入属性值。
假设Bean显示定义了一个带参的构造函数,则需要同时提供一个默认无参的构造函数,否则使用属性注入时将抛出异常。
public class UserServiceImpl2 implements IUserService {
private String name;
private Integer age;
private Date birthday;
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void queryAll() {
System.out.println(name+","+age+","+birthday+".");
}
}
<bean id="UserService2" class="com.imis.service.impl.UserServiceImpl2">
<property name="age" value="18"></property>
<property name="name" value="mike"></property>
<property name="birthday" ref="now"></property>
</bean>