Java,spring程序中实时获取.properties属性key的value

来源:互联网 发布:网络电影播放器 编辑:程序博客网 时间:2024/06/16 11:08


方法一:

 public static String getValue(String fileNamePath, String key)throws IOException {          Properties props = new Properties();          InputStream in = null;          try {              in = new FileInputStream(fileNamePath);              // 如果将in改为下面的方法,必须要将.Properties文件和此class类文件放在同一个包中              //in = propertiesTools.class.getResourceAsStream(fileNamePath);              props.load(in);              String value = props.getProperty(key);              // 有乱码时要进行重新编码              // new String(props.getProperty("name").getBytes("ISO-8859-1"), "GBK");              return value;            } catch (IOException e) {              e.printStackTrace();              return null;            } finally {              if (null != in)                  in.close();          }      }



方法二:

通过spring配置properties文件

<bean id="propertyConfigurer"  class="com.hapishop.util.ProjectDBinfoConfigurer">  <property name="ignoreResourceNotFound" value="true" />  <property name="locations">      <list>          <value>app.properties</value>      </list>  </property></bean>

自定义类PorpertiesConfigurer 

import java.util.HashMap;import java.util.Map;import java.util.Properties; import org.springframework.beans.BeansException;import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; public class PorpertiesConfigurer extends PropertyPlaceholderConfigurer {    private static Map ctxPropertiesMap;     @Override    protected void processProperties(            ConfigurableListableBeanFactory beanFactoryToProcess,            Properties props) throws BeansException {        super.processProperties(beanFactoryToProcess, props);        ctxPropertiesMap = new HashMap();        for (Object key : props.keySet()) {            String keyStr = key.toString();            String value = props.getProperty(keyStr);            ctxPropertiesMap.put(keyStr, value);        }    }    public static Object getContextProperty(String name) {        return ctxPropertiesMap.get(name);    }}


续:关于程序中加载spring,自定义类实现spring 配置文件中通配符${jdbc.name}类似的正确解析,有大神说是重载PropertyPlaceholderConfigurer中的resolvePlaceholder(String placeholder, Properties props) 方法,但是看源码API说明,改方法仅是从传入的properties中获取参数一placeholder的值,是否可行,等之后做了osgi框架中,继承到spring的时候便可知道。我目前觉得是

  1. processProperties(  
  2.             ConfigurableListableBeanFactory beanFactoryToProcess,  
  3.             Properties props)

方法是干这事儿的。




下面是转载另外一位博友的文章:


<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 25.2000007629395px; background-color: rgb(255, 255, 255);">在Spring初始化时,可以使用Properties配置器把properties文件装载到Spring的上下文中。</span>

 Xml代码  收藏代码

  1. ...  
  2. xmlns:context="http://www.springframework.org/schema/context"  
  3.   
  4. xsi:schemaLocation=“http://www.springframework.org/schema/context  
  5.                 http://www.springframework.org/schema/context/spring-context-3.0.xsd”  
  6.   
  7. ...  
  8.   
  9. <context:property-placeholder location="classpath:dataSource.properties" />  

 

这样在Spring的配置文件中可以用表达式来获得load进来的properties内容,例如:

 

Xml代码  收藏代码
  1. <property name="url" value="${url}" />  
  2. <property name="username" value="${username}" />  
  3. <property name="password" value="${password}" />  

 

有时候我们在程序中也需要用到这些配置,那么如何取值,显然不能使用${}方式的。

这时要决定用什么方式来获取properties了,最方便的当然是直接读取文件,此处省略。

如果程序一定要用通过Spring加载的properties,那么我们首先要得到Context了。

 

1、FileSystemXmlApplicationContext——从指定的目录中加载:

 

Java代码  收藏代码
  1. ApplicationContext context = new FileSystemXmlApplicationContext("applicationContext.xml");  

 

2、ClassPathXmlApplicationContext——从classpath路径加载:

Java代码  收藏代码
  1. ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  

 

3、参照http://blog.csdn.net/dqatsh/article/details/3469278, 通过web.xml来获取Context。

 

4、在servlet中获取。

 

Java代码  收藏代码
  1. ServletContext servletContext = servlet.getServletContext();     
  2. WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  

 

然后可以通过相应的bean去访问需要的properties(spring配置文件中${}方式设置到bean里)的值,这里不记录。

 

用PropertyPlaceholderConfigurer在加载上下文的时候暴露properties

 

Java代码  收藏代码
  1. <bean id="configBean"   
  2.  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   
  3.             <property name="location">   
  4.                 <value>hello.properties</value>   
  5.             </property>   
  6. </bean>   

 

表明PropertyPlaceholderConfigurer是承担properties读取任务的类。

 

下面的类继承PropertyPlaceholderConfigurer,通过重写processProperties方法把properties暴露出去了。

 

Java代码  收藏代码
  1. import java.util.HashMap;  
  2. import java.util.Map;  
  3. import java.util.Properties;  
  4.   
  5. import org.springframework.beans.BeansException;  
  6. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;  
  7. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;  
  8.   
  9. public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {  
  10.   
  11.     private static Map<String, Object> ctxPropertiesMap;  
  12.   
  13.     @Override  
  14.     protected void processProperties(ConfigurableListableBeanFactory beanFactory,  
  15.             Properties props)throws BeansException {  
  16.   
  17.         super.processProperties(beanFactory, props);  
  18.         //load properties to ctxPropertiesMap  
  19.         ctxPropertiesMap = new HashMap<String, Object>();  
  20.         for (Object key : props.keySet()) {  
  21.             String keyStr = key.toString();  
  22.             String value = props.getProperty(keyStr);  
  23.             ctxPropertiesMap.put(keyStr, value);  
  24.         }  
  25.     }  
  26.   
  27.     //static method for accessing context properties  
  28.     public static Object getContextProperty(String name) {  
  29.         return ctxPropertiesMap.get(name);  
  30.     }  
  31. }  

 

这样此类即完成了PropertyPlaceholderConfigurer的任务,同时又提供了上下文properties访问的功能。

于是在Spring配置文件中把PropertyPlaceholderConfigurer改成CustomizedPropertyConfigurer

 

Xml代码  收藏代码
  1. <!-- use customized properties configurer to expose properties to program -->  
  2. <bean id="configBean"   
  3.     class="com.payment.taobaoNavigator.util.CustomizedPropertyConfigurer">  
  4.     <property name="location" value="classpath:dataSource.properties" />  
  5. </bean>  

 

最后在程序中我们便可以使用CustomizedPropertyConfigurer.getContextProperty()来取得上下文中的properties的值了。


0 0
原创粉丝点击