Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Spring bean is singleton scope?

Tags:

spring

I am working with Hibernet and Spring it's going good..but I have some doubts

1) why spring scope is singleton by default?Is there any reason for that

2) Can I write final varible in Hibernate entity? Example :

@Entity
public class Emp {
  @Id
  private Long id;
  final private String panNo;
}

Can I write like above

3) static varibles can Searlizable?

like image 493
user2963481 Avatar asked Feb 17 '14 12:02

user2963481


2 Answers

If you look at Spring closely enough, you'll see that Spring helps you write services, NOT data objects. With Spring, you still have to manage your own domain objects, may it be relational data objects or straight POJOs, and pass them to a Spring managed service, repository, and controller etc as input.

So, with that in mind, it should be clear why Spring's default scope is NOT prototype, session, or request: we don't need to create a new service every time a request comes in. But why singleton? When a service is stateless, it's thread-safe, and it can scale to any number of concurrent requests, so there's no need for a second copy of the same service.

Unlike EJB, where there's stateful and stateless beans, Spring has only one type of bean: stateless. If you want to manage state, you'll have to do it yourself. And like previous answer has already pointed out, stateless is by far the better choice because it's faster, more scaleable and easier to maintain, it's also what REST architecture promotes. Stateful beans may appear great on paper, it has been proven over the years as quite a disaster.

like image 173
Christopher Yang Avatar answered Sep 19 '22 15:09

Christopher Yang


Stateless beans rules :) If you're not going to hold state data in beans then it's enough to have only one instance of each bean. You should also remember that it's not JVM singletons - just Spring singletons. So you don't have to provide only private constructor and any getInstance() methods.

Quote from Spring documentation:

When a bean is a singleton, only one shared instance of the bean will be managed and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned.

Only when you have to keep some session details you should use for example session scope.

like image 23
Jakub Kubrynski Avatar answered Sep 22 '22 15:09

Jakub Kubrynski