專案裡總有一些不想寫死在程式碼中的設定:伺服器位址、連接埠、開關參數。把這些放進配置檔是標準做法。以下整理四種常見的讀取方式,並指出各自的適用時機與陷阱。
四種做法都會用到同一個目標物件:
package chb.demo.vo;
public class HelloBean {
private String helloWorld;
public String getHelloWorld() {
return helloWorld;
}
public void setHelloWorld(String helloWorld) {
this.helloWorld = helloWorld;
}
}
最直覺的方式,適合配置檔放在 classpath 上的情況:
ApplicationContext context = new ClassPathXmlApplicationContext("beanConfig.xml");
HelloBean helloBean = (HelloBean) context.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
需要從檔案系統明確路徑載入時使用:
Resource rs = new FileSystemResource(
"D:/software/tomcat/webapps/springWebDemo/WEB-INF/classes/beanConfig.xml");
BeanFactory factory = new XmlBeanFactory(rs);
HelloBean helloBean = (HelloBean) factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
要特別注意:用 FileSystemResource 時,配置檔必須放在專案直接目錄下,或者寫出絕對路徑,否則會丟出找不到檔案的例外。相對路徑的解析基準是 JVM 的啟動目錄,換環境部署時很容易出錯,因此正式環境建議優先用 classpath 方式。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"https://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean" class="chb.demo.vo.HelloBean">
<property name="helloWorld">
<value>Hello!chb!</value>
</property>
</bean>
</beans>
先準備屬性檔,命名規則是「別名.class 指定類別來源,其餘行是屬性」:
helloBean.class=chb.demo.vo.HelloBean helloBean.helloWorld=Hello!chb!
然後用 PropertiesBeanDefinitionReader 載入:
BeanDefinitionRegistry reg = new DefaultListableBeanFactory();
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(reg);
reader.loadBeanDefinitions(new ClassPathResource("beanConfig.properties"));
BeanFactory factory = (BeanFactory) reg;
HelloBean helloBean = (HelloBean) factory.getBean("helloBean");
System.out.println(helloBean.getHelloWorld());
其中的 helloBean 就是 Bean 的別名設定,.class 用於指定類別來源。
如果只是讀幾個設定值,不需要 Spring 的 Bean 生命週期,直接用 JDK 的 Properties 最簡單。假設有個 ipConfig.properties:
ip=192.168.0.1 port=8080
讀取程式:
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("ipConfig.properties");
Properties p = new Properties();
try {
p.load(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println("ip:" + p.getProperty("ip") + ",port:" + p.getProperty("port"));
用 getClassLoader().getResourceAsStream() 而非絕對路徑,是讓程式碼在不同部署環境都能找到檔案的關鍵。
InputStream 一定要關閉,寫成 try (InputStream in = ...) 可避免漏關造成的檔案描述符耗盡。Reader 指定 UTF-8,或直接使用 YAML 搭配 Spring Boot 的設定機制。