`
qiuguo0205
  • 浏览: 240966 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

将 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

 

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

 

分享到:
评论
1 楼 javapub 2011-12-01  
Good, very useful. ecpecially the calss "Configuration "

相关推荐

Global site tag (gtag.js) - Google Analytics