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

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.

Related

Standard Scope for Spring classes

In a spring MVC app , by default all beans are singleton ,but what should be the standard scopes for below classes according to good programming practices:
1.DAO classes
2.Controller classes
3.DTO classes
4.Service classes
I have read that DAO and Controller classes should be singleton scoped and DTO classes should not be beans so not annotated, whenever required, DTO classes should be instantiated using "new".
What will be the scope of #Service classes ?
And Which classes will have the Request and Session scopes if none of the above classes are created in these 2 scopes?
First of all not classes, but Spring managed beans have a scope. Difference is that you can have classes in your application that you didn't configure to be managed by Spring (So for example you didn't provide #Component annotation)
For the Spring managed beans default scope is Singleton. That means Spring container will provide the same instance everytime you ask for that bean to be autowired.
You can change that default scope with for example #Scopeannotation. So to answer your question, all of the above mentioned choices would have default scope of singleton but you could changed that to be requestor sessionscope if you would like (only applicable in web applications though). You can read more about setting scopes here.
ps. DTO classes are usually not declared to be managed by Spring - letting Spring manage a simple data transfer object doesn't make much sense.
So basically two things to consider here. The 1st is that if a bean is required to be declared as a spring bean . It depends on if you need to use the spring features for this class such as #Transactional , #Async , #PreAuthorize , #Autowired (i.e dependency injection) , or ensure the bean has certain scope etc. If not , it is simpler not define it as a spring bean and simply create it by yourself.
So the following types of the classes are required to define them as spring bean in most cases:
DAO because most probably need to inject EntityManager or JdbcTemplate to it
Controller because it is a part of spring-mvc and you need to define it as a bean such that you can use #RequestMapping / #GetMapping / #PostMapping / #PutMapping / #DeletMapping / #PatchMapping etc. on its method.
Service class because you need to inject it into the controller and you need to use #Transactional to manage the DB transaction for its method.
For DTO , in most case you can create it by yourself since it is just a data container in nature and does not require to use any spring features.
The 2nd thing to consider is what scope does a bean should be. You mainly need to think about if an instance of that class is okay to be executed safely by multiple request (i.e thread) concurrently. If yes , you can simply use the default singleton scope. If not , you can think about if you want each HTTP request (i.e #RequestScope) or each HTTP session (i.e. #SessionScope) has their own instance of that class to work with. For example , if you are implementing some shopping cart , you most probably want that the HTTP session has their won instance of a shopping cart and so you should use #SessionScope for the shopping cart.

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.

Java Spring bean scopes: singleton vs application

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.

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

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