首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Struts2 系統常數管理:.properties + 靜態類最佳實踐

     編輯:程式設計疑難解答

需求:系統配置(樣式、服務器 IP 等)需在 JSP 與 Action 中共用,且修改後不想重新編譯部署。

方案架構

  1. 建立 config.properties:
    system.theme=blue
    server.ip=192.168.1.100
    support.email=admin@example.com
  2. 單例載入類:
    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";
    }
  3. 使用場景:
    • Action:String theme = SysConfig.get(SysConfig.THEME);
    • JSP(EL):${sysConfig['system.theme']} 需將 SysConfig 暴露到 Application 或用 TagLib。

優勢

  • 修改 .properties 即時生效(若啟用檔案監聽熱載入更佳)。
  • 無硬編碼,集中管理,型別安全。
  • 避免 Session 過期、Application 重啟丟失問題。

進階

結合 Spring @PropertySource + @ConfigurationProperties 實現型別安全注入,支援多環境 config-dev/prod.properties。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved