Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 167 Vote(s) - 3.65 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Should service layer classes be singletons?

#1
I am using Spring framework. Should my service classes be created as singletons? Can someone please explain why or why not? Thanks!
Reply

#2
Spring is easier to use if you stick with singleton-scoped beans. Singletons are its "default position", if you like. Yes, it supports other scopes (using `scope="xyz"` in the XML file), but it makes things harder to use and hurts performance.

Essentially, unless you have a good reason to do otherwise, stick with singletons.
Reply

#3
Yes, they should be of scope `singleton`.
Services should be stateless, and hence they don't need more than one instance.

Thus defining them in scope `singleton` would save the time to instantiate and wire them.

`singleton` is the default scope in spring, so just leave your bean definitions as they are, without explicitly specifying the `scope` attribute.

You can read more about scopes <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes">in the spring docs</a>.
Reply

#4
You need mostly singletons. (Spring default.) Singletons must be thread-safe, because parallel requests will use the same single instance. In fact, they must be completely stateless, because it can be destroyed and recreated at any time.

If you need to keep track of state inside of your bean (you should not, this should be in the database or stored in the request), you will get many instances of the same type of bean, memory usage goes up with the number of requests, whereby with singletons you will still have just one instance.

Even if you scope you beans to a request, they must still need be at least thread-safe (requests coming from the same browser at the same time).
Reply

#5
Service layer should be Singleton, otherwise for every incoming request a new object will be created and these objects are heavy contains business logic and lots of line of code. They must be Singleton.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through