Why Spring controllers are singleton for REST implementations? - spring

In case of REST implementations in Spring, spring Controllers are singleton. I want to know why spring controllers are singleton apart from thread-safety issue. Please help in resolving this issue.

This has nothing to do with REST.
Spring beans are, by default, singleton scoped. Since component scanning a #Controller annotated class simply generates a bean, that bean will be singleton scoped.
For reasons why a #Controller bean should be stateless, read any and all of the following:
Are Spring MVC Controllers Singletons?
Controller's life-cycle in Spring MVC
To follow up on the REST question, REST is meant to be stateless. In other words, each request contains all the information it needs for the server to handle it. Knowing that, it's pointless for the server (or #Controller) to keep any information after it's finished handling the request in instance fields and the like. Therefore a singleton is the way to go.

Related

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.

Issue in understanding the Spring Bean Scopes Vs Spring web flow Session Scopes

We Know the Spring Framework gives
singleton,
prototype,
request,
session,
global_session
bean Scopes.
Also we know that Spring web flow gives flowScope,viewScope,requestScope,flashScope,conversationScope.
So If i mentioned one Component, say Student, as #Component #Scope=singleton in a spring MVC project. For each request, will it create a new Student Object or Spring container will create only once?
You are confusing yourself with objects and beans.
For each request, will it create a new Student Object or Spring container will create only once?
The functioning of Spring is purely using beans. When you declare a something like a #Component, it's just an annotation that tells Spring that the part you've declared as a component is either Model or View or Controller i.e. a component of MVC. When you say something like #Scope=singleton, it tells Spring that only a single object instance can access the bean.
Let me make it more clear. Say you and I are objects and a strawberry candy is a bean. So if you have the candy. I cannot take it from you. Meaning only one of us can have that candy. It's the same thing with singleton scope.
Hope I made things simpler.. :)

Spring injection and object instantiation

I am trying to better understand Spring instantiation of beans. To illustrate my doubts, let's assume we have a Service class being wired in a Controller, here are the questions:
How will Spring manage the lifecycle
of the Controller? Will a new object
be created per request?
Once a Service is instantiaded and
wired to a Controller, will Spring
re-use that object reference to wire
it in to other beans?
Like Servlets, Controllers' lifecycle spans beyond requests. All of controllers in the application are instantiated only once when application is started; afterwards those objects are re-used to service all requests.
As Bozho pointed out, by default all beans are in singleton scope, therefore they will be re-used everywhere, unless specified otherwise.
The default scope is singleton, which means beans will be re-used (i.e. 1) no, a new object will not be created per request, and 2) yes, the object reference will be reused).
This can all be configured. Have a look at http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-scopes.
It all depends on the bean scope. By default all beans are in singleton scope - that is, they are instantiated by the container only once.
If you specify #Scope("request") (or the xml equivalent) then the same service object (singleton) will be injected in all instances of the request-scoped controller. (But you rarely need request-scoped controllers)

Stateful beans and Stateless beans in Spring context

I am reading spring through its official documentation and at one place I came to a line that uses prototype scope for all stateful beans while singleton for stateless beans.
I know there is something as stateful as well as stateless beans in EJB but this is not what they have mentioned in the documents.
Can anyone explain to me what exactly this means of stateful as well stateless beans in Spring
Thanks in advance
From spring perspective
stateless beans: beans that are singleton and are initialized only once. The only state they have is a shared state. These beans are created while the ApplicationContext is being initialized. The SAME bean instance will be returned/injected during the lifetime of this ApplicationContext.
stateful beans: beans that can carry state (instance variables). These are created EVERY time an object is required (like using the "new" operator in java).
These are not EJB statfull/stateless session beans.
There is no point in storing specific information like client data, per request data in Singleton bean as they are created only once by Spring IOC container. That's why singleton beans are stateless. They are shared resources. They can only be used for storing global information.
When a request is made for creating a prototype bean, a new request is created every time. So, they can be used to store some specific information for each request. So they are stateful.
It totally depends on the implementation. See tomee for example http://tomee.apache.org/statelesscontainer-config.html . You'll have to check in your server docs

Plain old singleton or spring singleton bean?

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.

Resources