Java Spring bean scopes: singleton vs application - spring

Could anyone explain the difference between these two Spring bean scopes?
I'm familiar with the Singleton pattern.
Would this be the only difference?
You can have a list of beans in the Spring container using application scope.
Also, are you able to run multiple web servers in one Spring container? If yes, that would be a reason to use the application scope over the singleton scope since otherwise the bean would get shared over the two servers.

The documentation explains it:
This is somewhat similar to a Spring singleton bean but differs in two important ways: It is a singleton per ServletContext, not per Spring 'ApplicationContext' (or which there may be several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute

In application scope, the container creates one instance per web application runtime.
The application scope is almost similar to singleton scope. So, the difference is
Application scoped bean is singleton per ServletContext however singleton scoped bean is singleton per ApplicationContext. It means that there can be multiple application contexts for single application.
SINGLETON SCOPED BEAN
//load the spring configuration file
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("context.xml");
// retrieve bean from spring container
MyBean myBean = context.getBean("myBean", MyBean.class);
MyBean myBean2 = context.getBean("myBean", MyBean.class);
// myBean == myBean2 - output is true.

Related

Does an Object in Spring created every time we write getBean()?

I have read that whenever we do getBean() in spring, it returns desired object.
So does it mean, if i write call getBean() 1000 times, thousand object will be created ??
If yes, Than how Spring manages these objects ?
if No, Please explain how Spring works with respect to object creation ?
Is there something Object pool kind of concept ?
Please clarify my doubts. I am new to spring and is very confused whether spring framework is created to make our task easy or to make things more complicated.
Spring seems to be a web of XMLs :(
From the Spring Framework documentation on singleton bean factory scope:
The singleton scope
Only one shared instance of a singleton bean is managed, and all
requests for beans with an id or ids matching that bean definition
result in that one specific bean instance being returned by the Spring
container.
To put it another way, when you define a bean definition and it is
scoped as a singleton, the Spring IoC container creates exactly one
instance of the object defined by that bean definition. This single
instance is stored in a cache of such singleton beans, and all
subsequent requests and references for that named bean return the
cached object.
To sum it up, no, Spring will create only a single instance of each bean in a bean factory unless you change the default scope of singleton to some other bean scope.
Other bean scopes include:
Bean scopes
singleton (Default) Scopes a single bean definition to a
single object instance per Spring IoC
container.
prototype Scopes a single bean
definition to any number of object instances.
request Scopes a single bean definition to the
lifecycle of a single HTTP request; that is, each HTTP request has its
own instance of a bean created off the back of a single bean
definition. Only valid in the context of a web-aware Spring
ApplicationContext.
session Scopes a single
bean definition to the lifecycle of an HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the
lifecycle of a global HTTP Session. Typically only valid when used in a portlet
context. Only valid in the context of a web-aware Spring
ApplicationContext.

ApplicationContext - Need clarification

I am new to springs and have the following queries on ApplicationContext.
1.What does it mean to declare two instances of classPathXmlApplicationContext on a single beans.xml file?
2.How is a beanPostProcessor programmatically associated with a single ApplicationContext?
1.What does it mean to declare two instances of classPathXmlApplicationContext on a single beans.xml file?
This would result in two different Spring application context unaware of each other. If there are any beans that are defined as singleton, each application context will now have its own instances of singleton beans, which means two bean instances one for each application context.
2.How is a beanPostProcessor programmatically associated with a single ApplicationContext?
To register a BeanPostProcessor you can add that to the spring configuration(xml/annotation) as a normal bean and spring will detect that automatically during the container startup and will invoke its callback methods during bean creation.
If you want to do this programatically, you can use BeanFactoryPostProcessor and addBeanPostProcessor method

Spring - what's a bean and what's not?

I'm new to Spring and I'm confused about something basic. Are the classes that are stereotyped (Service, Controller, Repository) treated as beans? I'm confused as to when you actually need to annotate/configure something as a bean and when you don't. Is it for the classes that aren't stereotyped?
Thanks!
From spring documentation:
In Spring, the objects that form the backbone of your application and
that are managed by the Spring IoC container are called beans. A bean
is an object that is instantiated, assembled, and otherwise managed by
a Spring IoC container. Otherwise, a bean is simply one of many
objects in your application. Beans, and the dependencies among them,
are reflected in the configuration metadata used by a container.
Service, Controller, Repository are managed by the Spring IoC container, so they are called beans. You annotate a class as #Serivice, #Controller, #Repository, or more in general #Component when you want spring to manage it: spring will manage the instance of annotated class in regard of the scope you select (not all these scope are always available):
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

Spring Beans Scope - taking into account Controllers \ Services \ Repositories

I'm having 1 #Controller bean in my project
and 2 #Service beans that this controller calls.
the services using 2 different #Repository beans for persisting.
My question is :
my server is about to get hundreds of calls simultaniously, isnt it "awkward" that all my beans i described above are of scope="singleton"? should i use "prototype" instead? or maybe spring does it automatically ?
I think in both cases you wil have the same number of objects.
The non-singleton, prototype scope of bean deployment results in the
creation of a new bean instance every time a request for that specific
bean is made (that is, it is injected into another bean or it is
requested via a programmatic getBean() method call on the
container). As a rule of thumb, you should use the prototype scope
for all beans that are stateful, while the singleton scope should be
used for stateless beans.
in Spring by default all beans it is "singleton" and should be in most cases.

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.

Resources