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

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

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.

Selecting the right candidates for spring bean. What to what not to

Last year when I started learning spring I remember an article that expalined that not all pojos are to be defined as beans. So I'm planning to create a web app say EmployeeMaintenance. CRUD Functionalities are there. I will surely end up creating pojos like Employee , EmployeeSupplementaryDetails, Address etc. Should I makes these beans and configure them in xml or annotate whatever. I'm sure my understanding of bean is not enough. I know that Dbconn , services etc should definitely be declared as bean.
All I need is what are the parameters I should consider before I make a pojo a Spring Bean.
General rule for making Java class a Spring bean is to ask yourself if you need to inject object into some other object or if you want the object to be managed by Spring components. The classes you listed as example doesn't seem to be good candidates for being Spring beans - they represent model data and will be passed as some service's methods parameters.
Examples of typical CRUD application beans:
EmployeeService (you would want to inject it to controller or other service)
EmployeeRepository / EmployeeDao
EmployeeController (it will be bean managed by Spring's MVC framework)
etc.
Spring beans are building blocks of your application. Let's suppose you need to create web application for storing and managing employees records (creating, retrieving, updating, deleting). What you will need is web controller that will handle incoming requests for several operations (EmployeeController). Good practice is that controller doesn't implement any business logic - all it should do is to delegate work to service beans. So you would need bean like EmployeeService. Then controller would ask service to do some work (give me employees list / remove John Smith from database / change salary for Ann Jackson / etc). So service will be controller's dependency (service is injected into controller). Service can also have some dependencies (like repository object, which is responsible for handling communication with data storage) and these dependencies would be injected to service. Dependency management is Spring's core feature.
Good practice in object oriented programming is to have small classes that are responsible for doing one kind of actions. Such objects are much easier to test and understand. The more classes you have, the building application from blocks is harder, so it's worth to delegate it to framework like Spring. Without Spring you would need to create controller class, then inside of it create service, then inside of it create other dependencies and so on. Spring does it for you, so all you need to do is to declare dependencies and they will be injected automatically. If you want to replace implementation of your service with another (for example repository that used XML file for storing data with repository storing data in relational database) then you just have to change your bean definition.
Regarding to beans managed by Spring, typical example is database transaction manager (eg. org.springframework.orm.jpa.JpaTransactionManager). If you define such bean, and declare which methods should be transactional, then Spring will take care of transactions management (will open, commit or rollback transactions automatically).

Spring MVC controller initialization code

I have a spring MVC project, in one of the controllers, i have a DB connection object that needs to be initialized only once in the controller, what is the best approach to follow when adding this initialization code, for now, i used a static block in the controller where i added the initialization code, do u have any other suggestions.
thanks in advance
Make it a Spring bean. That way it's a singleton (by default), and can be injected wherever you want.
Note that even if you leave its initialization in the controller, making it static is useless, since a controller is also a Spring bean, which is a singleton by default.
Well in spring you don't need to initialize the db connections yourself , It provide support for db connections
You just need to specify the the bean in .xml files and directly autowired that bean into your controller
use dao pattern to implement database connections see some example it will be easy container will manage db connections object life cycle for you
Thanks,
Himanshu
May I recommend you read the Spring reference guide for Object Relational Mapping and Data Access? Its quite comprehensive and details how to set up a data source, session factory, implement DAO classes, transaction management etc... Hopefully you will find this is a good place to start.

Why Spring controllers are singleton for REST implementations?

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.

Scenario when we may be needing #Configurable in spring?

I have question about the need of using #configurable. I have gone through the blog that explains how to use #configurable. But the question that comes to my mind is, what can be the scenario when we need to use #configurable. I can think of two scenarios where it can be useful
In a legacy project, when we are already making any bean with new operator and we want to make it spring managed.
In a new project, we want to enforce that even if developer makes the bean with new operator, still it is spring managed.
Otherwise for new beans we can always declare them in applicationContext.xml and I do not see any need to declare them #configurable.
Please let me know if above understanding is correct or if I am missing something.
UPDATE:- Basically as per my understanding configurable is generally used to inject dependency when creating the object with new operator. But why would i be creating the object with new operator when i am using spring
#Configurable annotation is meant for injecting dependencies in domain-driven applications. That means, in such applications, the domain objects interact with each other to perform a certain operation.
Take the following example:
In an invoicing application, the Invoice class provides a constructor to create it, then it has methods to validate, and finally persist it. Now, to persist the invoice, you need a DAO implementation available within the invoice. This is a dependency you would like to be injected or located. With Spring's #Configurable, whenever an invoice is created using the new operator, the appropriate DAO implementation will get injected and can be used for all persist operations.
I had a more realtime scenario where I used #Configurable annotation as described here.

Resources