在一个应用中,需要将 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
则运行程序将打印出这句话
本文介绍如何在Spring框架中通过静态工厂方法将Java.util.Properties类型的Bean注入到目标类中,并展示了具体的实现步骤与配置文件。
921

被折叠的 条评论
为什么被折叠?



