需求:系統配置(樣式、服務器 IP 等)需在 JSP 與 Action 中共用,且修改後不想重新編譯部署。
config.properties:
system.theme=blue
server.ip=192.168.1.100
support.email=admin@example.com
public final class SysConfig {
private static Properties props = new Properties();
static {
try (InputStream is = SysConfig.class.getResourceAsStream("/config.properties")) {
props.load(is);
} catch (IOException e) { throw new ExceptionInInitializerError(e); }
}
public static String get(String key) { return props.getProperty(key); }
// 常用 key 定義常數,避免硬編碼
public static final String THEME = "system.theme";
}
String theme = SysConfig.get(SysConfig.THEME);${sysConfig['system.theme']} 需將 SysConfig 暴露到 Application 或用 TagLib。.properties 即時生效(若啟用檔案監聽熱載入更佳)。結合 Spring @PropertySource + @ConfigurationProperties 實現型別安全注入,支援多環境 config-dev/prod.properties。