当 Action 需要注入 request 作用域 Bean 时,如何配置 Spring 的 scoped-proxy?

解读

国内项目普遍把 Struts2 Action 交给 Spring 托管,以便享受 AOP、事务、作用域等能力。
Action 默认是 prototype 作用域,而需要注入的 Bean 可能是 request 作用域(如封装当前请求参数的 CurrentUserHolder)。
由于 Spring 在启动时只创建一次 Action 实例,request 作用域 Bean 在容器启动期尚不存在,直接注入会抛出 ScopeMismatchException。
因此必须借助 aop:scoped-proxy/ 或 @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS),让 Spring 注入一个“代理对象”,该代理在每次方法调用时动态从当前线程绑定的请求里取出真实 Bean,从而解决“长生命周期对象引用短生命周期对象”的经典问题。

知识点

  1. 作用域错位:singleton/prototype Bean 引用 request/session Bean 会触发 Scope 'request' is not active 异常。
  2. scoped-proxy 本质:CGLIB 生成的子类代理,实现 ScopedObject 接口,内部通过 RequestContextHolder 获取当前 ServletRequestAttributes。
  3. 配置方式:
    • XML:<bean id="currentUser" class="com.xxx.CurrentUser" scope="request"><aop:scoped-proxy/></bean>
    • 注解:@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
  4. 必要条件:
    • web.xml 已配置 RequestContextListener 或 DispatcherServlet(把请求绑定到 ThreadLocal)。
    • 依赖 spring-aop 与 cglib 包,且不能被 <aop:aspectj-autoproxy proxy-target-class="false"/> 强制为 JDK 动态代理。
  5. 生命周期:代理对象跟随 singleton Action,目标 Bean 跟随 HTTP request,请求结束即销毁,内存无泄漏。
  6. 性能:代理仅方法级拦截,一次请求内多次调用只产生一次 getBean("currentUser") 开销,可忽略。
  7. 陷阱:
    • 在 Quartz 线程 或 @Async 线程中调用代理方法会再次触发 Scope not active,需手动设置 RequestAttributes。
    • 若 Bean 实现 final 类或 final 方法,CGLIB 无法代理,启动即报错。

答案

步骤一:确保 web.xml 已注册请求感知监听器

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

步骤二:定义 request 作用域 Bean 并开启 scoped-proxy
XML 风格:

<bean id="currentUser" class="com.xxx.CurrentUser" scope="request">
    <aop:scoped-proxy/>
</bean>

注解风格:

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CurrentUser { ... }

步骤三:在 Action 中正常注入

@Controller("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport {
    @Autowired
    private CurrentUser currentUser;   // 注入的是 CGLIB 代理

    public String execute(){
        // 每次请求都会拿到当前请求对应的 CurrentUser 实例
        currentUser.setUserId(123);
        return SUCCESS;
    }
}

步骤四:验证
启动应用,连续两次访问 /user.action,观察 currentUser 的 hashCode 每次不同,证明代理成功。

拓展思考

  1. 如果项目使用 Struts-Spring-Plugin 的 class="spring" 方式,Action 由 Spring 创建,上述配置完全适用;若仍用 class="struts" 方式,Action 由 Struts 自己 new,则无法注入 Spring 代理,必须改为全 Spring 托管。
  2. 在 Spring Boot + Struts2 的混合架构下,可用 @RequestScope + @Lazy 组合,但 @Lazy 仅延迟初始化,不能解决作用域错位,仍需 @Scope(proxyMode = TARGET_CLASS)。
  3. 对于 session 作用域 Bean,同理使用 <aop:scoped-proxy/>,但需注意集群环境下 session 复制 导致 Bean 重新序列化,代理类必须实现 Serializable。
  4. 若不想引入 CGLIB,可手动编写 ObjectFactory<CurrentUser> 并在 Action 中注入 Provider<CurrentUser>,每次 provider.get() 显式从请求中获取,这也是 Spring 官方推荐的 JSR-330 替代方案。