一、构造器的三种方式
//通过下标赋值
<bean id="user" class="com.lizheng.pojo.User">
<constructor-arg index="0" value="lizheng"/>
</bean>
//通过数据类型赋值,不建议使用,若两个参数均为string
<bean id="user2" class="com.lizheng.pojo.User">
<constructor-arg type="java.lang.String" value="rourou"/>
</bean>
//通过参数名来赋值
<bean id="user3" class="com.lizheng.pojo.User">
<constructor-arg name="name" value="junjun"/>
</bean>
二、通过set方法创建bean
<bean id="student" class="com.lizheng.pojo.Student">
<property name="name" value="lizheng"/>
<property name="address" ref="address"/>
<property name="card">
<map>
<entry key="id" value="200101"/>
</map>
</property>
<property name="games">
<set>
<value>lol</value>
</set>
</property>
<property name="wife">
<null/>
</property>
<property name="hobbies">
<list>
<value>basketball,football</value>
</list>
</property>
<property name="info">
<props>
<prop key="phone">1758900987</prop>
<prop key="gender">man</prop>
</props>
</property>
</bean>
<bean id="address" class="com.lizheng.pojo.Address">
<property name="address" value="中国"/>
</bean>
实体类:
public class Student {
private String name;
private Address address;
private List<String> hobbies;
private Map<String,String> card;
private Set<String> games;
private Properties info;
private String wife;
public String getWife() {
return wife;
}
public void setWife(String wife) {
this.wife = wife;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getCard() {
return card;
}
public void setCard(Map<String, String> card) {
this.card = card;
}
public Set<String> getGames() {
return games;
}
public void setGames(Set<String> games) {
this.games = games;
}
public Properties getInfo() {
return info;
}
public void setInfo(Properties info) {
this.info = info;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address=" + address +
", hobbies=" + hobbies +
", card=" + card +
", games=" + games +
", info=" + info +
", wife='" + wife + '\'' +
'}';
}
}
测试类:
@Test
public void myTset(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.getName());
System.out.println(student.getAddress());
System.out.println(student.getCard());
System.out.println(student.getInfo());
System.out.println(student.getHobbies());
System.out.println(student.getGames());
}