Action类可以限定为Singleton吗?

问题描述:

我的问题不仅仅是动作类可以限定为单例,而且我还想知道哪些是最佳实践。两者都在Struts2和Spring的背景下。控制器和模型的最佳VIEW范围(比如请求或会话)。

My question is not only if action classes can be scoped to singleton, but I also want to know which are the best practices. Both in context of Struts2 and Spring. Best scope of VIEW (say request or session), for controller and model.


  1. Struts2操作由Struts容器管理。它们是ThreadLocal,因此每个请求都有自己的Action的线程安全副本。

  1. Struts2 Actions are managed by the Struts Container. They are ThreadLocal, hence every request has its own thread-safe copy of the Action.

如果你使用Spring通过 Struts2-Spring-plugin ,有多种使用级别:

If you use Spring to handle them through the Struts2-Spring-plugin, there are multiple levels of usage:


  • 你可以让Struts容器实例化它们,并通过Spring处理它们以进行依赖注入,或者

  • 你可以让Spring接管它们控制并对每个行动的整个生命周期负全部责任。
    在第二种情况下:


    • 如果在Spring XML配置文件中将操作声明为bean,则操作将获得默认的Spring范围,这是Singleton( scope =singleton)。这是危险的,无用的,99.99%的时间不是你想要的,因为你将失去框架能力的基本部分,行动将变成种类的servlet,线程 - UNsafe,并且会出现许多问题;

    • 为了防止这种情况,你可以在bean声明中放入 scope =prototype,这样就可以让Spring实例化影响其性质。

    • you can let the Struts container instantiate them, and handle them through Spring for the Dependency Injection, or
    • you can let Spring take over control and be fully responsible for the whole lifecycle of every Action.
      In this second case:
      • if you declare an action as a bean in a Spring XML configuration file, the action will get the default Spring scope, that is Singleton (scope="singleton"). THIS IS DANGEROUS, USELESS, and 99.99% of the times NOT WHAT YOU WANT, because you will lose a fundamental part of the framework capability, actions will be turned into kind-of servlets, thread-UNsafe, and many problems will arise;
      • to prevent that, you can put the scope="prototype" in the bean declaration, that will let Spring instantiate the action without affecting its nature.

      如果你在容器Java EE中6+兼容(例如,Jboss 7,Wildfly 8,TomEE 1.7,Glassfish 3 +,ecc ...),上下文和依赖注入通过CDI处理。如果需要,您可以使用 Struts2-CDI-plugin 来允许CDI通过 @处理您的操作并注入依赖项注入 注释(而不是 @Autowired 一个)

      If you are inside a container Java EE 6+ compliant (for example, Jboss 7, Wildfly 8, TomEE 1.7, Glassfish 3+, ecc...), the Contexts and the Dependency Injections are handled through CDI. If you want, you can use the Struts2-CDI-plugin to allow CDI to handle your actions and inject dependencies through the @Inject annotation (instead of the @Autowired one)

      我过去经常使用Spring,然后在发现CDI和CDI插件后,我已经切换并且从未回头,所以我投票给n.3

      I've used Spring a lot in the past, then after discovering CDI and the CDI plugin, I've switched and never looked back, so I vote for the n.3