在Spring中配置bean的属性参数时,可以使用外部的properties文件,步骤如下:
1.在Spring配置文件中(一般是applicationContext.xml),在beans标签中引用配置,如下:
“xmlns:context=”http://www.springframework.org/schema/context””
在Myeclipse中可以直接在Namespaces中直接勾选(可视化编辑xml)
2.准备相应的properties文件,后缀为.properties时,Myeclipse中会变成相应的图标。在properties文件中编辑相关属性, key=value。
3.使用<context:property-placeholder>
标签,在location属性中指定相应的properties文件路径,记得在前面加上clssspath:
4.在<bean>
标签中,property的value值使用EL表达式获得,如value=”${id}”,与直接在property中直接写出value的值效果一样
相关的applicationContext.xml代码如下:
<?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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:propertyplaceholder location="classpath:com/spring/d_outsideproperty/pro.properties"/>
<bean id="user" class="com.spring.d_outsideproperty.User">
<property name="id" value="${id}"/>
<property name="name" value="${name}"/>
<property name="single" value="${single}"/>
</bean>
</beans>
过程中有个问题,就是properties文件中貌似只能是String类型的值,关于是否可以是其他类型的值,可以的话怎么转型,这些后续了解到再上来改下~