Spring:读入properties文件程序示例
项目目录结构
properties文件
位于prop/custom.properties
abc="hello"
xml文件
位于conf/ioc.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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<util:properties id="custom" location="classpath:prop/custom.properties" />
<bean id="dog" class="ioc.DogServiceTest" >
<property name="custom" ref="custom"></property>
</bean>
</beans>
此处用了util作用域,第11行定义了一个bean,类型为java.util.Properties
java文件
位于ioc/DogServiceTest.java
package ioc;
import java.util.Properties;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DogServiceTest {
private static Properties custom;
public void setCustom(Properties custom) {
DogServiceTest.custom = custom;
}
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[]{"conf/ioc.xml"});
System.out.println(DogServiceTest.custom);
}
}
输出:{abc="hello"}