Can an Action class be scoped to Singleton?

前端 未结 1 1785
故里飘歌
故里飘歌 2020-12-10 00:28

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

1条回答
  •  时光说笑
    2020-12-10 00:40

    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

    0 讨论(0)
提交回复
热议问题