本文详解 Struts2 中如何像 Spring Boot 的 application.properties 一样集中管理应用级配置(如 applicationId、timeout),介绍 struts.properties、全局资源包(struts.custom.i18n.resources)及自定义 TextProvider 等核心机制,并说明纯标识类配置的安全存储原则。
本文详解 struts2 中如何像 spring boot 的 `application.properties` 一样集中管理应用级配置(如 `applicationid`、`timeout`),介绍 `struts.properties`、全局资源包(`struts.custom.i18n.resources`)及自定义 `textprovider` 等核心机制,并说明纯标识类配置的安全存储原则。
在 Struts2 中,虽无原生的 @Value 或 @ConfigurationProperties 注解支持,但通过其成熟的国际化(i18n)资源机制与配置加载体系,完全可以实现灵活、可维护的应用级属性管理。关键在于区分两类用途:
- 框架级配置(如默认编码、开发模式开关):应写入 struts.properties(位于 src/main/resources/)或 struts.xml 的 <constant> 元素中;
- 业务级应用属性(如 applicationId、api.timeout、service.endpoint):推荐使用全局消息资源包(Global Resource Bundles),即标准 .properties 文件(如 application.properties),并通过 struts.custom.i18n.resources 声明加载。
✅ 推荐实践:使用全局资源包管理业务属性
-
创建配置文件
在 src/main/resources/ 下新建 application.properties:# application.properties application.id=prod-7a2f9e api.timeout=30000 service.base-url=https://api.example.com/v2
-
注册为全局资源包
在 struts.properties 中添加:struts.custom.i18n.resources=application
注意:application 是文件名(不含 .properties 后缀)。Struts2 会自动加载 application_en_US.properties、application_zh_CN.properties 等本地化变体,但若仅需单语言配置,基础文件即可生效。
-
在 Action 中安全读取值
继承 ActionSupport 的 Action 类可直接调用 getText() 方法(该方法底层由 TextProvider 实现,支持占位符和类型转换):public class ApiCallAction extends ActionSupport { private String appId; private int timeout; @Override public String execute() throws Exception { this.appId = getText("application.id"); // 返回 String this.timeout = Integer.parseInt(getText("api.timeout")); // 手动转换(建议封装工具类) // ... 调用第三方 API return SUCCESS; } // getters/setters... }
⚠️ 注意事项与最佳实践
安全性说明:对于不包含密码、密钥、Token 等敏感凭证的纯标识类属性(如 applicationId、timeout、feature.flag),以明文形式存于 application.properties 是安全且符合惯例的。该文件随 WAR 包部署,不暴露于 Web 路径(确保 web.xml 未开放 /resources/* 或类似静态资源路径对 *.properties 的直接访问)。
避免误用 struts.properties 存业务属性:struts.properties 专用于框架行为控制(如 struts.devMode=true)。将业务键值混入其中会降低可读性,且无法利用 getText() 的统一查找逻辑(它只扫描 i18n.resources 指定的 bundle)。
-
进阶:自定义 TextProvider(按需)
若需从数据库、Consul 或加密 Vault 动态加载配置,可实现 TextProvider 接口并替换默认实现:<!-- struts.xml --> <constant name="struts.localizedTextProvider" value="com.example.CustomTextProvider" />
需确保 CustomTextProvider 正确实现 getText(String key) 和 getText(String key, String[] args),并线程安全。
-
类型安全增强建议:Struts2 原生 getText() 返回 String,建议封装工具类做类型转换与默认值兜底:
public static int getInt(String key, int defaultValue) { try { return Integer.parseInt(ActionContext.getContext().getActionInvocation() .getAction().getText(key)); } catch (NumberFormatException e) { return defaultValue; } }
综上,Struts2 的 i18n.resource 机制不仅是多语言支持方案,更是成熟可靠的应用配置中心。合理使用 struts.custom.i18n.resources + getText(),即可获得媲美 Spring Boot 的外部化配置体验,同时保持架构清晰与生产安全性。










