在springboot項目的開發中,當需要讀取src/下的配置文件時,該怎么做?
Resources下有一個文件名為acceptsNum.xls的模板文件
1.在java類中讀取
若配置文件不在src/main/resources目錄下,可以直接使用
- Properties prop = new properties();
- prop.load(new InputStream("acceptsNum.xls"));
當配置文件放在src/main/resources的目錄下時,只能使用Class.getResourceAsStream()方法來加載
- Properties prop = new properties();
- 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中讀取一個甚至多個配置文件。
- <bean id="kafkaService" class="com.wws.service.impl.KafkaServiceImpl">
- <!-- <property name="topic"><value>topic</value></property> -->
- <property name="topic"><value>${kafka.topic}</value></property>
- </bean>
這樣就可以在后面的bean中成功調用配置文件中的參數,以上被注釋的那段property和被注釋掉的那行是同樣效果
2).或者也可以使用如下方法
- <context:property-placholder location="classpath:kafka.properties"/>
直接在spring配置文件中配置context:property-placeholder,有多個配置文件可以用逗號隔開,例如
- <context:property-placeholder location="classpath:kafka.properties,classpath:jdbc.properties"/>
