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 are managed by the Struts Container. They are ThreadLocal, hence every request has its own thread-safe copy of the Action.
If you use Spring to handle them through the Struts2-Spring-plugin, there are multiple levels of usage:
- 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.
- 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 (
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)
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