如何在 Struts 常量中开启 SpringObjectFactory 并验证 Action 实例由 Spring 容器创建?

解读

国内大多数基于 Struts2 的老系统都跑在 Spring + Hibernate 全家桶上,面试官问这道题,核心想确认两件事:

  1. 你知不知道 Struts2 默认用 ObjectFactory 创建 Action,而 Spring 插件要替换为 SpringObjectFactory;
  2. 你有没有真正在生产环境排查过“Action 到底 new 出来的还是 Spring 容器给的”,而不是只会背配置。
    答不出“验证”环节,基本会被判定为“只配写 XML 的 CRUD boy”。

知识点

  1. struts.objectFactory 常量:Struts2 启动时由 Dispatcher 读取,决定用哪个 ObjectFactory 实现。
  2. struts-objectfactory-spring-*.jar 必须先进 classpath,否则常量配了也 ClassNotFound。
  3. SpringObjectFactory 实现了 ObjectFactory 接口,把 Bean 的实例化委托给 ApplicationContext。
  4. 验证原理:Spring 创建的 Bean 必定走过 AbstractAutowireCapableBeanFactory#doCreateBean,内存地址里可看到 CGLIB 增强子类 或 @Scope 代理,且 ActionSupport 的依赖字段不为 null。
  5. 国内项目 90% 用 xml 方式 配常量,10% 用 struts.properties;注解方式(@Constant)极少,因为老项目 JDK7/8 居多,升级风险高。

答案

  1. 在 struts.xml 根节点下增加常量配置,顺序必须在 package 之前,否则被 package 级覆盖:
<constant name="struts.objectFactory" value="spring" />
  1. 确保 struts2-spring-plugin-*.jar 已引入 Maven:
<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-spring-plugin</artifactId>
    <version>2.5.30</version>
</dependency>
  1. 在 web.xml 中配置 Spring 监听器,保证 ContextLoaderListener 比 StrutsPrepareAndExecuteFilter 先启动:
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  1. 验证步骤(面试时可直接口述,证明你干过):
    a. 给 Action 加 @Scope("prototype") 或 xml 里写 scope="prototype";
    b. 在 Action 的默认构造函数里打印 this.getClass().getName();
    c. 发送一次请求,观察日志:若输出类名包含 EnhancerBySpringCGLIBEnhancerBySpringCGLIB,则证明是 Spring 代理对象;
    d. 断点打在 SpringObjectFactory#buildBean,能看到 ApplicationContext#getBean() 被调用,而非 Class.newInstance();
    e. 若去掉 struts.objectFactory=spring,重复请求,断点不再进入 Spring 容器,Action 字段注入全为 null,即可反向验证。

拓展思考

  1. 如果项目里同时出现 @Controller 和 struts.xml 里 class 全限定名 冲突,Spring 容器会报 NoUniqueBeanDefinitionException,此时要用 @Qualifier 或在 struts-plugin.xml 中指定 struts.objectFactory.spring.autoWire=name,把自动装配策略改为 byName,避免误注入。
  2. 国内很多银行系统仍用 Struts2.3.x,该版本插件默认 autoWire=type,一旦 Action 有多个同类型依赖就会启动失败,升级成本大,常规做法是 关闭自动装配,改为 手动注入:
<constant name="struts.objectFactory.spring.autoWire" value="no" />
  1. 面试官可能追问:“prototype 会不会导致 Spring 容器爆炸?” 正确答法是:Struts2 每次请求都会 new Action,Spring 的 prototype 正好匹配,但 不会缓存,因此内存占用只与并发量成正比,与容器无关;若改成 singleton,则会出现 线程安全 问题,绝对禁止。