Should service layer classes be singletons? - spring

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

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 in the spring docs.

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.

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).

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.

Related

How concurrency works in SpringBoot when the default lifetime of objects is singleton

In ASP.NET the default lifecycle of objects created in IoC container is per web request. While learning SpringBoot + Webflux, I found that the default lifecycle (Bean, Repository, Service, etc) created by the IoC container is singleton. I know I can change the default scope like this:
#Scope("prototype")
but I have not yet found an example where it would be used. So if IoC creates all object as singletons, how come there are no problems with concurrency. Can someone please explain this to me.
It's a good question. Generally speaking where concurrency is an issue, for example a transaction context in the database layer, springbook uses a thread based locking mechanism. See for example 1.2. Understanding the Spring Framework Transaction Abstraction. Otherwise, yes, anything injected with CDI is a singleton unless specifically annotated otherwise. That means that you should not keep state variables in your #Component or #Service classes. As long as the methods use only parameters passed in or variable local to the method concurrency isn't an issue because ever variable is created on the stack which is unique for each call. I have seen an application work great up until the day two people log in at once.
If you have to have a class with state variables you need to do a new of that class.
Each spring-context is created with a unique thread, so where objects are created or injected that are not stateless then state information is attached to the spring-context which runs in its own thread.
See also How does Spring bean Handle concurrency

Using correctly the #Scope annotation is Spring 3 web application

I recently readed carefully about the spring mvc 3 beans scope, specifically the web ones(session, request and global session) and i have some doubdts:
If i have a controller, why should i annotate him with other scope aside of singleton? I mean, the controllers are supossed to handle the requests and instantiate the view resources of all the app, so why give them a, for instance, session scope? what is the advantage of do that?
Is advisable making the services layer session scoped?
And finally, is there any convention or good practices that dictates where and when is more convenient the use each one of the web scopes? If there is, can somebody provides me the link or information about it? Not necessary convention or good practices, also your experience about it.
Thanks very much.
I mean, the controllers are supossed to handle the requests and
instantiate the view resources of all the app, so why give them a, for
instance, session scope?
In an average web application, you have various objects that exist on a per-session basis. Example can be user profile, or some kind of cabinet, or wallet, etc.
To be able to use those objects in service, every time you should get from session, and pass through the service chain. Instead of doing this, of course it is better to have those available in your service, without a need to pass it explicitly.
Really good example (in practice) you can find here.
An ideal practical example of request scope bean is HttpServletRequest, which should be unique obviously for each request, therefore it is request scoped and created for each request.
From my experience, without any explicit need for a case, you don't need to bother yourself with changing scopes. It is not without reason that default scope is Singleton, it is by purpose - because in most of the applications and basic scenarios you need beans as singleton. However as your main concern was with Session and Request scopes, the above examples are cases which you need often in web application.

Is a singleton REST database resource a good idea?

Here's my situation. I have a class called somethingDao that contains all my logic for querying a table.
Then, I also have somethingDaoResource, which is a Jersey API resource, but also a Singleton, and is instantiating a somethingDao object via Spring (i.e., I'm injecting a datasource into somethingDao).
Then, I have a Jersey API businessLogicResource that does:
somethingDaoResource.getInstance().getsomethingDao() which gets me the somethingDao object at which I then fire multiple queries.
My question is, is this considered a good design? My main concern is that every time someone sends a HTTP request to my businessLogicResource, if the somethingDaoResource wasn't a Singleton (or a static?), then that would create a new instance of somethingDao, and open a new connection, which takes a while to do.
Any suggestions are more than welcome.
PS - I also have a c3p0 connection pool.
The most common practice is to have DAO objects as stateless singletons. Instead of opening and closing a connection they would borrow one from a pool and then return it when done. You can limit the maximum number of connections in the pool.
Having something statefull and a singleton in a web application is usually a bad idea. It might cause all kinds of read/write conflicts or thread locking. This approach also kills any possibility of distributing your application over a number of servers, which breaks one of the REST architectural constraints.

Spring core container is the basis for complete Spring framework?

All websites state that the Spring core container is the basis for complete Spring framework i.e., it is used across
the all modules like AOP, JDBC module, Web module, etc. As per my understanding, the Spring core container's main purpose is
to inject dependencies, so avoiding the need of factory classes and methods. Is that correct?
Second question: When it is said, Spring core container is the basis for complete Spring framework (e.g., for Spring AOP). As per my understanding, in Spring AOP also, getting the object of classes like
ProxyFactoryBean is achieved by core container. Right?
Thirdly, it is stated that Spring core container avoids the need for programming the use of singletons. How come singleton
classes are avoided by core container?
yep
yep
All beans declared in Spring config files are singleton by default. They are instantiated when your application starts.
First off, your understanding of what you get from Spring is about right. So let's get on to your third question, the interesting one.
The key is it's not that you don't have singletons, it's that they're singletons by configuration. This is a vital difference, as it means you can avoid all the complicated singleton enforcement code (the source of frequent problems) and instead just write exceptionally simple programs that focus on the business end of things. This is particularly important when you are writing a program with non-trivial object lifetimes: for example, in a webapp it makes it very easy to manage the lifespan of objects that hold state associated with a user's session, since if the objects have session scope, they'll be “singleton per user session”. That's enormously easier to work with than many of the alternatives.
The fact that Spring can also help out with transactions is just perfect as transaction handling is distinctly non-trivial, and AOP is the best solution to them in Java that I've seen (other languages have other options open) with Spring supporting a pretty straight-forward way of doing it. Try to do it properly without if you don't believe me. Spring's pretty much wonderful.

Inversion of Control, Spring Framework - system of global instances

Is inversion of control essentially just retrieving a set of already instantiated objects? In theory. I guess more granular details as implemented by IoC frameworks like Spring have a lot more functionality, but in theory it seems like IoC containers operate like a collection of instantiated beans (in the Java world) and then you get access to those beans. Almost like you would with a collection Singleton objects?
It's partly getting hold of singletons in practice, yes. Some beans will be instantiated multiple times, whenever they're needed (depending on the configuration), but often you can make do with single instances - particularly if they're stateless once configured. I like the idea of data flowing "through" an application's plumbing after it's been properly hooked up.
The benefit is that the "singletoneity" is only present in the configuration, not in the code, which makes the system more testable and flexible. The difference in terms of how you view (and expose) the dependencies with your app is huge.
Although the answer has already been accepted, I will elaborate a little more:
Initially spring was mostly about singleton management. with the introduction of custom scopes came the web specific scopes and the ability to create your own custom scopes. Leaning on AOP features this also allows you to "stay singleton" for as long as possible, because it uses a technique known as scope proxying. This can let you introduce a scoped object right in the middle of a chain of singletons - a feature you'd often be using threadlocals for.
So I'd say it's about tight control of instance creation, to make sure everything is done only the required number of times, and preferably only the construction that is necessary is done for each request. Singleton management was the old days.

Resources