Spring 读取properties文件

传统 方式可以配置 

<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样 -->
   <property name="locations">
       <array>
          <value>classpath:jdbc.properties</value>
       </array>
   </property>
</bean>

 使用 @Value方式读取,这种方式每次都得需要声明一个变量

所以使用如下方式:

创建一个PropertiesUtils 继承 PropertyPlaceholderConfigurer

如下

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class PropertiesUtils extends PropertyPlaceholderConfigurer {
	 private static Map<String,String> propertyMap;

	    @Override
	    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) {
	        super.processProperties(beanFactoryToProcess, props);
	        propertyMap = new HashMap<String, String>();
	        for (Object key : props.keySet()) {
	            String keyStr = key.toString();
	            String value = props.getProperty(keyStr);
	            propertyMap.put(keyStr, value);
	        }
	    }

	    //static method for accessing context properties
	    public static Object getProperty(String name) {
	        return propertyMap.get(name);
	    }
}	

在spring中如下配置:

 <!-- 读取properties文件 -->
    <bean id="proptiesConfig" class="com.campus.utils.PropertiesUtils">  
	    <property name="locations">  
	        <array>  
	            <value>classpath:resource.properties</value> <!-- 可以是多个文件 --> 
	            <!-- <value>classpath:resource2.properties</value> -->  
	        </array>  
	    </property>  
	</bean>  

然后在 java 中可以通过如下方式访问

String value= (String) PropertiesUtils.getProperty("upload.photo"); //这里的 upload.photo 
//是在properties文件中的key


如properties文件如下:

aaa=D:\\TestM\\photo
bbbb=D:\\TestM\\video

则String value= (String) PropertiesUtils.getProperty("aaa");
得到value 值为  D:\\TestM\\photo

猜你喜欢

转载自1960370817.iteye.com/blog/2396958