将 java.util.Properties 作为参数传入Spring [初级]

在一个应用中,需要将 java.util.Properties 作为参数传入 一个类中,并读出其中的一个参数

 

package cn.com.test.spring.properties;

import java.util.Properties;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PropertyTest {
	
	private Properties pro;

	public void setPro(Properties pro) {
		this.pro = pro;
	}

	public Properties getPro() {
		return pro;
	}
	
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("context_test_property.xml");
		PropertyTest test = (PropertyTest)context.getBean("PropertyTest");
		System.out.println(test.getPro().get("testString"));
	}
}

 

如何将java.util.Properties以一个Bean的形式传入该类呢?可以使用Spring的静态工厂方法:

首先定义一个类实现一个返回 Properties的静态方法:

 

package cn.com.test.spring.properties;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class Configuration {
	private static Properties pro = null;

	public static Properties getProperties(String propertyFile)
			throws FileNotFoundException, IOException {
		if (pro == null) {
			pro = new Properties();
			pro.load(new FileInputStream(propertyFile));
		}
		return pro;
	}
}

 

 然后在配置文件中注册这个静态工厂方法即可

 

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

	<bean id="PropertyTest" class="cn.com.test.spring.properties.PropertyTest">
		<property name="pro" ref="prop" />
	</bean>

	<bean id="prop" class="cn.com.test.spring.properties.Configuration"
		factory-method="getProperties">
		<constructor-arg
			value="E:\Project\Java\Spring\springstudy\src\test.properties" />
	</bean>
</beans>

 

如果在src的根路径下有文件test.propertie,其内容是:

testString=this is a test string for the test of a property file

 

则运行程序将打印出这句话

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值