Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

java - Can an Action class be scoped to Singleton?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...