一般来说javaBean对象的属性大多设为私有的,同时也配有相应的get和set方法。那么spring就可以借助其set方法,为其属性注入相应的值
新建一个班级类:
public class Class {
private String name = "testClass";
public String getName() {
return name;
}
}
新建一个学生类:
public class Student {
private String name;
private Class stuClass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Class getStuClass() {
return stuClass;
}
public void setStuClass(Class stuClass) {
this.stuClass = stuClass;
}
}
在spring的配置文档当中可以利用<property>元素配置bean的属性。
①如果为bean注入简单的值,比如说字符串,数字等,可以直接为<property>设置value属性。
②如果为bean注入对象,引用其他bean。那么可以为<property>设置ref属性,其值就是其他bean的id值。(ref注入,也可以改为<property>的内部bean)
③spring还提供了命名空间p来替代<property>为bean注入属性。想使用命名空间p,需要在配置中增加xmlns:p="http://www.springframework.org/schema/p"
具体的配置例子如下:
<?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="tClass" class="com.test.beanSet.Class"/>
<!-- property注入属性,如果是引用对象,那么可以利用ref来注入 -->
<bean id="tStudent" class="com.test.beanSet.Student">
<property name="name" value="Xiao Ming"/>
<property name="stuClass" ref="tClass"/>
</bean>
<!-- 除了ref注入对象,还可以直接在property中配置内部bean -->
<bean id="tStudent2" class="com.test.beanSet.Student">
<property name="name" value="Xiao Hong"/>
<property name="stuClass">
<bean class="com.test.beanSet.Class"/>
</property>
</bean>
<!-- 另外可以使用命名空间p来替代property -->
<bean id="tStudent3" class="com.test.beanSet.Student" p:name="Xiao Li" p:stuClass-ref="tClass"/>
</beans>
测试代码:
public class BeanSetApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("testBeanSet.xml");
Student tStudent = (Student) context.getBean("tStudent");
System.out.println(tStudent.getName());
System.out.println(tStudent.getStuClass().getName());
Student tStudent2 = (Student) context.getBean("tStudent2");
System.out.println(tStudent2.getName());
System.out.println(tStudent2.getStuClass().getName());
Student student3 = (Student) context.getBean("tStudent3");
System.out.println(student3.getName());
System.out.println(student3.getStuClass().getName());
}
}
运行结果:
Xiao Ming
testClass
Xiao Hong
testClass
Xiao Li
testClass