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

相關文章
相關標籤/搜索