java讀取項目中模板文件(src/main/resources)


在springboot項目的開發中,當需要讀取src/下的配置文件時,該怎么做?

Resources下有一個文件名為acceptsNum.xls的模板文件 

1.在java類中讀取
若配置文件不在src/main/resources目錄下,可以直接使用

  1. Properties prop = new properties();  
  2. prop.load(new InputStream("acceptsNum.xls"));  

當配置文件放在src/main/resources的目錄下時,只能使用Class.getResourceAsStream()方法來加載

 
  1. Properties prop = new properties();  
  2. prop.load(this.getClass().getResourceAsStream("/acceptsNum.xls"));  
InputStream is = null;
is = this.getClass().getResourceAsStream("/static/xls/acceptsNum.xls");

此時,getResourceAsStream(String name)方法中參數路徑的寫法:

1).若寫成"acceptsNum.xls",則是去當前類的class文件同一目錄下找(但是顯然在正常項目不會有人將配置文件放在這種位置)。

2).若寫成"/acceptsNum.xls",則是去整個項目的classes目錄下去找,即target/classes

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

2.在spring框架的xml文件中讀取配置文件kafka.properties

 

以下就有兩種方法來調用

1).首先可以在spring的bean中配置

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  

<property name="locations">  

<list

<span style="white-space:pre">  </span><value>/kafka.properties</value

</list>  

</property

</bean>  

這里還可以在list標簽中配置多個value,這樣就可以在bean中讀取一個甚至多個配置文件。

 
  1. <bean id="kafkaService" class="com.wws.service.impl.KafkaServiceImpl">  
  2.     <!-- <property name="topic"><value>topic</value></property> -->  
  3.     <property name="topic"><value>${kafka.topic}</value></property>  
  4. </bean>  

這樣就可以在后面的bean中成功調用配置文件中的參數,以上被注釋的那段property和被注釋掉的那行是同樣效果
2).或者也可以使用如下方法

 
  1. <context:property-placholder location="classpath:kafka.properties"/>  

直接在spring配置文件中配置context:property-placeholder,有多個配置文件可以用逗號隔開,例如

    1. <context:property-placeholder location="classpath:kafka.properties,classpath:jdbc.properties"/> 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM