Plain old singleton or spring singleton bean? - spring

I have a service in my application which is a singleton.
My application is being bloated with the use of spring framework.
I am confused over to use the singleton service as
1: Plain Old Singleton [Access them statically when required]
OR as a
2: Spring singleton bean. [Use DI to inject when required]
Which approach is correct ?

The Spring singleton scope is not the same as the Singleton design pattern, which is not the same as a class with static methods.
From the documentation
"Please be aware that Spring's concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hardcodes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition."
Also, note you need to be very careful using a Spring singleton as a service that web requests will utilize. Since each request is on its own thread, you can have threading issues if your singleton maintains any state.
To answer your question: Create a class that implements an interface, and use Spring to DI it appropriately. If your service does not maintain state, you can scope it to singleton, otherwise you can scope it to prototype.

I use Spring's beans whenever possible. The framework was designed to manage these things, and it is probably better than me at it. Another reason to use Spring's dependency injection is the possibility to unit-test with mocks instead of the real utility code, thus focusing the unit-test to the exact scope.
EDIT:
To answer the question in the comment, the only case I can think of for a non-bean singleton would be a utility code class, which would contain short pieces of generally reusable code in public static methods. Anything else requires instantiation, and therefore - a bean.

Related

why #RestController by default use singleton scope?

I am actually a EJB developer and very new in spring framework.
i find a couples of conflict conceptually. Like ..
#RestController use by default scope which is singleton. By single object per loc have to manage heavy trafic.
is it a good design?
Of course, it is a good design because the same instance of the object will be reused instead of keep creating it each time you need it. That is the whole point of that design pattern.
Here is a great example where singleton comes to the rescue.
https://rules.sonarsource.com/java/RSPEC-2119
By default, spring will take care of the creation and destruction of all singleton beans, while the prototype has to be manually handled. Therefore in a lot of cases prototype scope is for custom beans made by developers.
In SpringMVC Controller layer, #Scope("prototype") vs #Scope("singleton")
is it a good design?
Yes, all beans in Spring are singletons (by default).
We have 100+ controllers in several applications and it works perfectly.
If you really need to instantiate controllers more than once, you can, of course, consider other bean scopes (see brief explanation of scopes here https://www.baeldung.com/spring-bean-scopes)

Which is better to implement a singleton in a Spring application: a bean or a static field?

I am developing Spring MVC app, i need to implement singleton pattern for some kind of utilities, ex: imageuploader and others.
My question is: in what way to implement singleton for this utilities, to initialize beans for these classes and inject where i need like Controllers, Services, DAO?, or to use static field implementation of singleton to keep instance of this class?
First, try to avoid singleton as it's considered to be a bad practice. Also their interactions with other instances are difficult to test and validate, compared to non-singleton instances.
If you absolutely need it, I'd suggest you use a Spring bean so you can exploit the autowiring mechanism and Spring's bean lifecycle.
See the Beans section of the Spring reference doc for more info.
Using a Spring bean as will allow you to easily inject a mock in unit tests. However, you will only be able to access it from other Spring beans (or objects created by Spring beans that pass in a reference to it).
Also see this discussion in this question: Difference between static class and singleton pattern?
Traditionally, you'd use PropertyPlaceholderConfigurer to inject config from properties files into a Spring web-app. This blog discusses a variety of newer ways to do this with Spring.

Use/Purpose of beans in Spring

Could someone give an overview or a summary of what the purpose of beans in a Spring framework context?
I understand the standard Java bean (no arg constructor, getters/setters, often serialized), but the Spring bean purpose seems to be different.
Is it a way of implementing the Singleton design pattern (one instance, for like factory classes) in a simple, reusable fashion?
I've mainly used Spring with annotations, but I feel I need to grasp this in order to understand Spring.
Thanks!
Beans are objects that form the backbone of the application.
A bean is simply an object that is instantiated, assembled and otherwise managed by a Spring IoC container; other than that, there is nothing special about a bean.It is in all other respects one of probably many objects in your application.
Spring beans are defined in a spring configuration file or by using annotations, instantiated by the Spring container, and then injected into your application.
Spring beans will not be singleton design pattern until you explicitly make them to be.The singleton design pattern and the spring scope 'singleton' are different things.You can define different bean scopes depending on your requirements.
The scopes could be :
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request.
session – Return a single bean instance per HTTP session.
globalSession – Return a single bean instance per global HTTP
session.
The default scope is singleton.
I understand the standard Java bean (no arg constructor,
getters/setters, often serialized), but the Spring bean purpose seems
to be different.
You mean always serialized. Why do you think the purpose seems different?
In the end, you write classes. A lot of time these are POJOs, Plain Old Java Objects. Sometimes you implement an interface or extend a class, but its all just classes.
Beans are just classes. Don't overcomplicate it.
Now Spring might take your beans (classes) and manage them for you via any of a number of policies (prototype, singleton) but that doesn't change what a bean is, it speaks to how Spring manages the bean.
To understand best, you should get familiar with dependency injection. In a few words dependency injection allows you to use objects, or services without explicitly creating them (of course, it gives other benefits, but let's focus on the question). This is achieved by maintaining a dependency container that is - roughly said - a collection of beans.
A bean is a service/component you use in your application. Unlike the EJB, with Spring the bean is not constrained to constructor arguments or specific annotations (especially if you use xml contexts). You register a bean with a container (by defining a context), and when you require it, the container will provide you with an instance of that bean. In order to create the bean, the container examines its class and constructors, and uses any other registered beans within that context, to call the appropriate constructor or property setter.
You can configure a bean to be a singleton - this is not a singleton as in the design pattern term. Singleton beans are created once within the container, and the same instance is used whenever the bean is requested from that container. You can also use the prototype scope to force the container to create a new instance each time.

What is the prototype Spring Bean used for?

By default, the Bean created by Spring is singleton. They are thread-safe because they are stateless. When we want Spring to create a stateful Bean, we need to use prototype scope for the Bean definition. We need to take care of the thread-safe issues for them. All stateless Bean will be polluted when they are injected by the prototype bean. So, I just can not image where we can use the prototype scope. Can you give some typical scenario that we can / need to use prototype Spring Bean? Also how can we void the stateful pollution on other singleton beans?
There are many reasons to use prototype scope, e.g., any time you'd use "new" instead of using a singleton. A per-user bean, a per-request bean, a collection of unique beans, etc. After all, in any non-trivial application, don't you use non-singletons far more than singletons?
Singleton-scoped beans aren't thread-safe simply because they're singletons–they must be written to be thread-safe. They don't become thread-safe magically. A bean's scope is just that, its scope: it doesn't make the bean appropriate for the particular scope–that's up to the developer.
I perceive prototype scoped beans as an alternative to factory classes used to create objects. The difference is in case of prototype beans spring will save you some code for dependency injection and will also automatically proxy your objects for transactions etc. when appropriate.
I myself prefer the factory approach. One reasonable scenario for prototype scope I encountered was a stateful object, needed by different known beans and each required its own copy. A dedicated factory class would be redundant in this scenario since I did not need to create objects on the fly but only during other beans' instantiation.

Can the object created in IoC container be called Singleton. If not - why?

can the object created in IOC container can be called Singleton if yes why if no why?
Can anybody explain me in detail in simple words how IOC conatiner exactly manages the objects..
You can say that a spring singleton is not a singleton.
Singleton has its meaningful scope, the spring singleton scope is the spring ioc container. And the classic singleton's meaningful scope is the ClassLoader. You may find more about the distinction between these kinds of singleton here: A spring singleton is not a singleton.
Spring manage its singleton in a hashmap(Singleton Cache). When you get a bean from the spring ioc container, it first checks if the bean has already exists in the singleton cache, if does, it returns the bean from the singleton cache
Spring (and other ioc-containers) offer different scopes. One of the scopes is singleton - i.e. the container instantiates the object only once and gives / injects only one instance. Singleton is the default scope, so most of the beans are indeed singletons from the point of view of the container- i.e. they have only one instance in it.
However, there are other scopes, like prototype or the web-based request and session.
In managing the bean, the container does the following:
invokes the #PostConstruct and #PreDestroy methods (or the init and destroy methods, configured by any available means)
injects all their defined dependencies (=sets other beans existing in the container to the fields of this bean)
creates AOP aspects around the bean methods
Note: you can instantiate more than one objects of a class that is defined as as singleton bean. The container instantiates the object only once, but your code is not limited to instantiating it multiple times.
can the object created in IOC
container can be called Singleton if
yes why if no why?
Read this, from the Spring Reference.
Can anybody explain me in detail in
simple words how IOC conatiner exactly
manages the objects..
Read this, from the Spring Reference.
I use a more generic definition of a Singleton:
A Singleton is an object that is
guaranteed to be unique inside a given
scope.
This scope is the ClassLoader in the traditional singleton definition, but other possible scopes are:
Application (may be clustered and therefor classic Singleton won't help)
HTTP Session
Thread (implemented through ThreadLocals)
HTTP Request etc.
(I really like the Seam method Component.getInstance(Class, ScopeType) that lets you choose the Scope you want a singleton for.)
You might find this Google Groups thread useful.

Resources