2012-07-10 66 views
0

我正在使用彈簧。我有一個外部化的屬性文件。我正在加載它如下。如何在會話範圍內保留屬性值?

<context:property-placeholder location="file:///C:/some.properties"/> 

現在我該如何保持會話中的屬性作爲鍵值對?

我試着編寫一個擴展了ServletContextListener的偵聽器。

public class Sample implements ServletContextListener { 
@Override 
    public void contextInitialized(ServletContextEvent event) { 
//here i tried to get the values of properties file as below. 
InputStream stream = event.getServletContext().getResourceAsStream("C:\\some.properties"); 
//But here stream is coming as null 


} 

} 

我在這裏丟失了什麼嗎?

謝謝!

回答

2

SetvletContextcontextInitlalized()時調用servlet上下文初始化時成功加載應用程序,

如果你想存儲它的屬性在應用程序上下文文件,你可以把它放在

event.getServletContext().setAttribute("global_properties", propertiesInstance); 

如果你需要每個會話,然後你需要將它掛接到HttpSessionListenersessionCreated()方法

因此,把經常使用的數據,這是共享acros s applicationscope中的應用程序和限於會話但經常使用的數據將它放在session

+0

感謝您的回覆。是加載外部化的屬性文件後調用contextInitlalized()?謝謝! – user1016403 2012-07-10 11:17:22

+0

不客氣(如果我真的回答了你的問題,那麼你可以upvote /標記答案接受:)) – 2012-07-10 11:18:20

1

我建議使用PropertyPlaceHolderConfigurer與ServletContextListner進行通信。此類PropertyPlaceHolderConfigurer有一個方法調用processProperties,您可以在其中獲取所有屬性的地圖。

@Override 
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, 
    Properties props) throws BeansException { 
    super.processProperties(beanFactoryToProcess, props); 
    resolvedProps = new HashMap<String, String>(); 
    for (Object key : props.keySet()) { 
     String keyStr = key.toString(); 

     resolvedProps.put(keyStr, parseStringValue(props.getProperty(keyStr), props, 
       new HashSet())); 
    } 
} 

而在聽者contextInitialized()你可以做這樣的:

ServletContext servletContext = sce.getServletContext(); 
    WebApplicationContext context = WebApplicationContextUtils 
      .getRequiredWebApplicationContext(servletContext); 
    ExposablePropertyPlaceHolder configurer =(ExposablePropertyPlaceHolder)context.getBean(propertiesBeanName); 
    sce.getServletContext().setAttribute(contextProperty, configurer.getResolvedProps()); 

其中ExposablePropertyPlaceHolder是延伸PropertyPlaceHolderConfigurer類。