(1)普通类型注入 value注入
有一个类Student:
public class Student
{
private String name;
}
//注意:使用setter注入(1)需要有相应的set方法的,比如setName,setAge方法
// (2)需要有无参的构造方法
//这里为了简化,没有写这个类的setName方法和无参构造方法
在beans.xml文件中:(创建一个Student对象,并且给它的name这个属性赋值)
//new一个对象叫作student,它来自Student类
<bean id="student" class="com.kuang.pojo.Student">
//给这个对象student的name属性赋值
<property name="name" value="欧阳水鸣"></property>
</bean>
测试:
//创建出beans.xml文件里面的所有bean,这些bean放到spring这个容器里面进行管理
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
//拿到这个叫做hello的bean
Student student= (Student) context.getBean("student");
System.out.println(student.getName());
(2)引用类型注入 ref注入
此时属性是一个对象,也就是说,一个类的对象是另一个类的属性
step1:先创建一个类B
public class B
{
private int height;
}
step2:再创建一个类A,类B的对象b是类A的属性
public class A
{
private B b;
}
//完整的话这里也应该有set方法和无参构造方法:
public class A
{
private B b;
//set方法
public void setB(B b)
{
this.b=b;
}
//无参构造方法
public void A
{
system.out.println("类A的无参构造方法.......");
}
}
step3:beans.xml这个文件中进行创建对象,给对象赋值
//创建三个B类的对象b1,b2,b3
<bean id="b1" class="com.kuang.pojo.B">
<property name="height" value="123"></property>
</bean>
<bean id="b2" class="com.kuang.pojo.B">
<property name="height" value="456"></property>
</bean>
<bean id="b3" class="com.kuang.pojo.B">
<property name="height" value="789"></property>
</bean>
//创建两个A类的对象a1和a2,a1对象有b属性,a2对象也有b属性
//给a1这个对象的b属性赋值b1
<bean id="a1" class="com.kuang.pojo.A">
<property name="b" ref="b1"></property>
</bean>
//给a2这个对象的b属性赋值b2
<bean id="a2" class="com.kuang.pojo.A">
<property name="b" ref="b2"></property>
</bean>
step4:测试类
public class MyTest
{
public static void main(String[] args)
{
//创建出beans.xml文件里面的所有bean,这些bean放到spring这个容器里面进行管理
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
//拿到a1和a2两个bean
A a1= (A) context.getBean("a1");
A a2= (A) context.getBean("a2");
System.out.println(a1.b.height);//123
System.out.println(a2.b.height);//456
}
}