7.5.4 设置普通属性值

7.5.4 设置普通属性值

使用元素的value属性

<property>元素的value属性用于指定基本类型及其包装类字符串类型的参数值, Spring使用XML解析器来解析出这些数据,然后利用java.beans.PropertyEditor完成类型转换:从java.lang.String类型转换为所需的参数值类型。如果目标类型是基本类型及其包装类,通常都可以正确转换。

程序示例

项目结构

1
2
3
4
5
6
7
8
9
10
E:\workspace_QingLiangJiJavaEEQiYeYingYongShiZhang5\value
└─src\
├─beans.xml
├─lee\
│ └─BeanTest.java
└─org\
└─crazyit\
└─app\
└─service\
└─ExampleBean.java

下面的代码演示了**<property>元素的value属性**确定属性值的情况。假设有如下的Bean类,该Bean类里包含int型和double型的两个属性,并为这两个属性提供对应的setter方法。下面是该Bean的实现类代码,由于仅仅用于测试注入普通属性值,因此没有使用接口.

ExampleBean.java

1
2
3
4
5
6
7
8
9
package org.crazyit.app.service;
public class ExampleBean
{
// 定义一个int型的成员变量
private int integerField;
// 定义一个double型的成员变量
private double doubleField;
// 此处省略getter和setter方法,请自己补上
}

上面Bean类的两个成员变量都是基本数据类型的, Spring配置文件使用<property>元素的value属性即可为这两个基本数据类型的成员变量对应的setter方法指定参数值。配置文件如下。

beans.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="GBK"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="exampleBean" class="org.crazyit.app.service.ExampleBean">
<!-- 指定int型的参数值 -->
<property name="integerField" value="1" />
<!-- 指定double型的参数值 -->
<property name="doubleField" value="2.3" />
</bean>
</beans>

BeanTest.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package lee;

import org.springframework.context.*;
import org.springframework.context.support.*;
import org.crazyit.app.service.*;
public class BeanTest
{
public static void main(String[] args)
{
// 以类加载路径下的bean.xml文件来创建Spring容器
@SuppressWarnings("resource")
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"beans.xml");
ExampleBean b = ctx.getBean("exampleBean", ExampleBean.class);
System.out.println(b.getIntegerField());
System.out.println(b.getDoubleField());
}
}

运行程序,输出exampleBean的两个成员变量值,可以看到输出结果分别是12.3,这表明Spring已为这两个成员变量成功注入了值。

使用元素的子元素

早期Spring还支持一个”更为臃肿”的写法,例如需要配置一个驱动类,如果用早期Spring的配置方式,则需要如下三行代码:

1
2
3
<property name="driverClass">
<value>com.mysql.jdbc.Driver</value>
</property>

而现在的Spring配置则使用如下一行代码接口实现:

1
<property name="driverClass" value="com.mysql.jdbc.Driver"/>

上面的这一行配置片段通过为<property>元素的value属性来指定调用setDriverClass()方法的参数值为com.mysql.jdbc.Driver,从而完成依赖关系的设值注入。这种配置方式只要一行代码即可完成一次”依赖注入”
两种方式所能提供的信息量完全一样,而采用value属性则更加简洁;所以后来Spring都推荐采用value属性的方式来配置。