基于XML的装配
import java.util.List;
public class User {
private String username;
private Integer password;
private List<String> list;
public User() { }
public User(String username, Integer password, List<String> list) {
this.username = username;
this.password = password;
this.list = list;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(Integer password) {
this.password = password;
}
public void setList(List<String> list) {
this.list = list;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", list=" + list + "]";
}
}
1. 通过setter方法注入
条件:Bean类中必须有默认无参的构造方法,和需要注入属性对应的setter方法。 使用的标签名 property 属性name 和 value 、name的值和属性名要一致 XML中的配置:
<bean id="user1" class="com.sanyi.User">
<property name="username" value="Jack"></property>
<property name="password" value="654321"></property>
<property name="list">
<list>
<value>"setListValue1"</value>
<value>"setListValue2"</value>
</list>
</property>
</bean>
2.通过构造方法定义
使用的标签有 constructor-arg 属性name 和 value
<bean id="user2" class="com.sanyi.User">
<constructor-arg index="0" value="Tom" />
<constructor-arg index="1" value="123456" />
<constructor-arg index="2" >
<list>
<value>"constructValue1"</value>
<value>"constructValue2"</value>
</list>
</constructor-arg>
</bean>
|