Spring:读入properties文件程序示例

项目目录结构

在这里插入图片描述

properties文件

位于prop/custom.propertiesjava

abc="hello"

xml文件

位于conf/ioc.xmlweb

<?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.Propertiesspring

java文件

位于ioc/DogServiceTest.javasvg

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"}spa