Action 类可以限定为 Singleton 吗?

Can an Action class be scoped to Singleton?(Action 类可以限定为 Singleton 吗?)

本文介绍了Action 类可以限定为 Singleton 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题不仅是动作类是否可以限定为单例,而且我还想知道哪些是最佳实践.在 Struts2 和 Spring 的上下文中.控制器和模型的最佳视图范围(例如请求或会话).

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 Actions 由 Struts Container 管理.它们是 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 接管控制权,并对每个 Action 的整个生命周期负全部责任.
    在第二种情况下:
    • 如果您在 Spring XML 配置文件中将操作声明为 bean,则该操作将获得默认的 Spring 范围,即 Singleton (scope="singleton").这是危险的、无用的,而且 99.99% 的时间都不是您想要的,因为您将失去框架功能的基本部分,动作将变成某种 servlet,线程不安全,并且会出现许多问题;
    • 为了防止这种情况,您可以将 scope="prototype" 放在 bean 声明中,这将使 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处理您的操作并通过 @Inject 注释(而不是 @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

      这篇关于Action 类可以限定为 Singleton 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Action 类可以限定为 Singleton 吗?

基础教程推荐