在Spring中属性的注入分为两种
构造函数的注入:
1.无参构造函数
2.有参构造函数
Set方式的注入:
创建set方法。
构造方法属性注入:
public class Student {
private int number;
private String name;
// 无参构造函数
public Student(){
}
// 有参构造函数
public Student(int number,String name){
this.name = name;
this.number = number;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [number=" + number + ", name=" + name + "]";
}
}
1.无参函数的
@Test
public void demo4(){
ApplicationContext ac = new ClassPathXmlApplicationContext("application_context.xml");
Student student = ac.getBean("student",Student.class);
System.out.println(student);
}
<bean id="student" class="com.liubo.service.impl.Student"></bean>
2.有参构造函数
<bean id="student1" class="com.liubo.service.impl.Student">
<constructor-arg type="int" name="number" index="0" value="1"></constructor-arg>
<constructor-arg type="java.lang.String" index="1" value="刘波"></constructor-arg>
</bean>
Student student = ac.getBean("student1",Student.class);
System.out.println(student);
Set方法属性注入:
<bean id="student2" class="com.liubo.service.impl.Student">
<property name="name" value="唐雨"></property>
<property name="number" value="123456"></property>
</bean>
Student student = ac.getBean("student2",Student.class);
System.out.println(student);