我的问题不仅是动作类是否可以限定为单例,而且我还想知道哪些是最佳实践.在 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.
Struts2 Actions 由 Struts Container 管理.它们是 ThreadLocal,因此每个请求都有自己的 Action 线程安全副本.
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:
scope="singleton"
).这是危险的、无用的,而且 99.99% 的时间都不是您想要的,因为您将失去框架功能的基本部分,动作将变成某种 servlet,线程不安全,并且会出现许多问题;scope="prototype"
放在 bean 声明中,这将使 Spring 实例化操作而不影响其性质.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; 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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!