2

I was going through spring tutorials and was looking at default scope of beans , so by default scope is singletone only. But when we use annotation in classes what scope they have ? do they create single object only for those class in JVM ? if yes than how web application works will it be thread safe ?

Arjun Prajapati
  • 263
  • 1
  • 2
  • 15
  • They're singletons. They're thread-safe because they typically are stateless, i.e. their only instance variables are references to other beans that are initialized at startup and never modified. Of course, if you don't know what you're doing and store mutable state in these singletons, they won't be thread-safe. – JB Nizet Jan 02 '19 at 18:00

2 Answers2

2

But when we use annotation in classes what scope they have?

They are singletons unless you use @Scope and specify a different scope.

Do they create a single object only for those class in JVM?

Spring creates one object per container. It's important since your JVM can run several Spring containers at once.

Will a web application be thread safe?

It's up to you. Spring can guarantee that lifecycle operations over a component are performed in a thread-safe manner (e.g. a bean instance is published thread-safely). However, Spring can't predict your application logic and how you define its correctness. For this reason, it doesn't provide any level of synchronisation, which might be insufficient or an overhead.

A good discussion on this part is here.

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
0

Every bean managed by Spring container has Singleton scope by default no matter either you use annotation or xml, unless you don't override its default one.

hitesh
  • 1
  • 2