bean类
package com.zxh.model;
public class Student {
private String username;
private String password;
private Integer id;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Student() {
}
public Student(String username, Integer id) {
this.username = username;
this.id = id;
}
public Student(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "Student{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", id=" + id +
'}';
}
}
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--构造方法注入属性值-->
<bean id="student1" class="com.zxh.model.Student">
<constructor-arg name="username" value="zxh"></constructor-arg>
<constructor-arg name="password" value="123456"></constructor-arg>
</bean>
<!--构造方法通过索引注入属性值-->
<bean id="student2" class="com.zxh.model.Student">
<constructor-arg index="0" value="zxh" type="java.lang.String"></constructor-arg>
<constructor-arg index="1" value="123456" type="java.lang.String"></constructor-arg>
</bean>
<!--set方法注入属性值-->
<bean id="student3" class="com.zxh.model.Student">
<property name="username" value="zxh"></property>
<property name="password" value="123456"></property>
<property name="id" value="12"></property>
</bean>
<!--p标签注入属性值-->
<bean id="student4" class="com.zxh.model.Student" p:id="10" p:username="zxh" p:password="123456"></bean>
</beans>
测试类
package com.zxh.test;
import com.zxh.model.Student;
import com.zxh.model.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class lesson06 {
@Test
public void test() throws Exception {
/**
* 给对象属性赋值的方式
*/
ApplicationContext ac = new ClassPathXmlApplicationContext("beans6.xml");
Student student = (Student) ac.getBean("student4");
System.out.println(student);
}
}