如何把 Struts 常量迁移到 application.yml?

解读

在国内企业级 Java 面试中,“把 struts.xml 中的常量搬到 Spring Boot 的 application.yml” 是高频追问。
面试官真正想确认的是:

  1. 你是否知道 Struts 2 只认 struts.xml 或 struts.properties 两种原生配置源;
  2. 你是否理解 Spring Boot 的 application.yml 并不是 Struts 的默认配置源;
  3. 你是否掌握 “把 yml 解析成 Properties,再喂给 Struts” 这一官方推荐套路;
  4. 你是否能在 零 XML、全 YAML 的潮流下,给出可落地的 Bean 定义与启动监听方案。
    答不到“必须借助自定义配置源”这一层,会被直接判定为“只用过 XML,没做过真迁移”。

知识点

  1. StrutsConstants:Struts 2 所有常量键值枚举,例如 struts.devMode、struts.i18n.encoding。
  2. ConfigurationProvider 扩展点:实现该接口可把任意来源(yml、db、redis)注入 Struts 容器。
  3. StrutsSpringBootstrap:Spring Boot 场景下由 struts2-spring-boot-starter 提供,内部已注册一个默认的 SpringConfigurationProvider。
  4. YamlPropertySourceLoader:Spring Boot 原生工具,可把 yml 解析成 PropertySource。
  5. 优先级顺序:struts.xml > struts.properties > 自定义 ConfigurationProvider;同键后者不会覆盖前者,因此必须禁用 XML 常量段才能完全迁移。
  6. 国内灰度实践:把 yml 拆成 struts.yml,利用 spring.profiles.include 做多环境隔离,配合 Nacos 配置中心热更新。

答案

步骤一:在 application.yml 中按扁平键值书写 Struts 常量,避免层级对象,防止 OGNL 解析失败。

struts:
  devMode: false
  i18n.encoding: UTF-8
  multipart.maxSize: 20MB
  action.extension: action,,
  configuration.xml.reload: true

步骤二:编写 YmlStrutsConfigurationProvider,实现 ConfigurationProvider 接口,把 Spring Environment 中的上述键值刷入 Struts 容器。

public class YmlStrutsConfigurationProvider implements ConfigurationProvider {
    @Override
    public void init(Configuration configuration) {
        ConfigurableEnvironment env = SpringContextHolder.getApplicationContext().getEnvironment();
        // 只提取 struts.* 前缀
        RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(env, "struts.");
        resolver.getSubProperties("").forEach(configuration::setParameter);
    }
    @Override
    public boolean needsReload() { return false; }
    @Override
    public void destroy() {}
}

步骤三:在 Spring Boot 启动类中,通过 @PostConstruct 把自定义 Provider 塞给 Struts。

@SpringBootApplication
@ImportResource("classpath:struts.xml") // 保留 Action 映射,但**去掉<constant>段**
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Autowired
    private ConfigurationManager strutsConfigurationManager;

    @PostConstruct
    public void injectYmlProvider() {
        strutsConfigurationManager.addConfigurationProvider(new YmlStrutsConfigurationProvider());
    }
}

步骤四:验证迁移成功
启动日志出现
INFO o.a.s.c.c.ConfigurationProvider: Loading struts constants from YmlStrutsConfigurationProvider
且 devMode=false 已生效,证明 XML 常量段已被 yml 完全替换。

拓展思考

  1. 动态刷新:结合 Spring Cloud @RefreshScope 与 Struts ConfigurationManager.reload(),可在 Nacos 改完 yml 后无重启热更新常量,适用于国内大促场景。
  2. 多租户隔离:把租户编码拼到 key 前缀,重写 YmlStrutsConfigurationProvider,实现租户级别常量(如 struts.tenantA.devMode=true)。
  3. 兼容老项目:若存量 struts.xml 常量过多,可先用 Maven 的 resource filtering 在打包阶段把 yml 值回写到 struts.properties,再逐步去 XML,实现灰度迁移。