2011-03-24 85 views
0

我正在使用CXF創建一個java web服務。如何讀取屬性文件?

我有一個文件路徑,例如「C:\ FTPROOT」,必須配置 ,所以我希望把這個路徑成性文件,例如爲application.properties

,但我怎麼能讀取屬性文件在我的java代碼?

任何人都可以幫忙嗎?

感謝

回答

0

你需要把屬性文件在您的resourcesWEB-INF/classes

然後

Properties properties = new Properties(); 
try { 
    properties.load(new FileInputStream("classpath:application.properties")); 
} catch (IOException e) { 
} 

請參見

+0

我想知道,是否有任何Spring鉤子允許'classpath:URL解析?一般來說,這個URL不應該在Java中工作(參見[本文])(http://stackoverflow.com/questions/7596155/not-able-to-load-properties-file-in-java/7596193#7596193)),除非你註冊URL處理程序,例如通過['URL.setURLStreamHandlerFactory()'](http://stackoverflow.com/questions/148350/how-to-register-url-handler-for-apache-commons-httpclient/148390#148390)或通過'java。 protocol.handler.pkgs'系統屬性。 – 2011-11-21 16:25:27

0

爲Spring創建一個PropertyPlaceholderConfigurer(請參閱API瞭解選項)。

實施例:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="searchSystemEnvironment" value="true"/> 
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/> 
    <property name="ignoreUnresolvablePlaceholders" value="true"/> 
    <property name="locations"> 
     <list> 
      <value>classpath:build.properties</value> 
      <value>classpath:other.properties</value> 
     </list> 
    </property> 
</bean> 

假設你有在屬性文件中的屬性file.path並且正在使用組件掃描則可以使用:

@Value("file.path") private String filePath; 

這將隨後與的值填充file.path在屬性文件中(如果bean是由Spring創建的)

或者如果您使用XML創建bean:

<bean class="yourClassName"> 
    <property name="filePath" value="${file.path} /> 
</bean>