1

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.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
Sandeep Deb
  • 51
  • 1
  • 8
  • 1
    please share your thoughts so far? what have you been researching and found out? what is your conclusion if any where is the doubt?... or you haven't and this a question for your exam? – Milan Dec 02 '15 at 19:38
  • Spring provide as default scope of singleton. However when we use struts with spring is it a good idea make action classes singleton because if we do so I will get the same instance of the bean. Also can anyone explain me"Singleton scope should be used with stateless session bean and prototype scope with EJB stateful session bean" Similar logic for action DAO,DTO,BS and interceptors. – Sandeep Deb Dec 02 '15 at 20:07
  • 1
    If for every user request you are server same action class (singleton) it has to be stateless otherwise all you users would share each other states! If you are using prototype scope spring will serve new instance of the bean for every request. http://docs.spring.io/spring/docs/3.1.0.M2/spring-framework-reference/html/beans.html#beans-factory-scopes-singleton – Milan Dec 02 '15 at 20:44

1 Answers1

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

  2. 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.
  3. 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

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243