0

How many times Spring is calling single Singleton constructor?

In which cases constructor can be called more than one time (for bean with the same id)?

EDIT:

HERE is an answer that user is telling that can be more than once - I need more explanation for that.

ByeBye
  • 6,650
  • 5
  • 30
  • 63

1 Answers1

0

How many times Spring is calling single Singleton constructor?

Only once; The default Bean Scope is singleton.

In which cases constructor can be called more than one time (for bean with same id)?

Take a look at Bean Scopes

Scope Description

singleton

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 and every HTTP request will have 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 a 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.

What you need is scope prototype

Spring Prototype Image

So add a @Scope("prototype") to your bean definition like this:

@Bean
@Scope("prototype") //add this
public MyBean myBean()
{
    return new MyBean();
}
Impulse The Fox
  • 2,638
  • 2
  • 27
  • 52
  • So you want to call `@PostConstruct` multiple times? – Impulse The Fox Mar 20 '18 at 07:50
  • No, I want to know why constructor to same bean can be called multiple times. – ByeBye Mar 20 '18 at 07:51
  • Are you now talking about `@PostConstruct` or really just the default Java constructor? If you mean the later, well why not? You can instantiate (and therefore call the constructor of) any class you like as many times as you like. – Impulse The Fox Mar 20 '18 at 07:54
  • I am not talking about calling constructor via `new`. I asked why `Spring` can call singleton's constructor (for bean with same id) more than once. I am not asking about PostConstruct. – ByeBye Mar 20 '18 at 07:55
  • So with constructor you mean the method annotated with `@Bean` returning a new instance of the bean? Spring won't call that more than once by default. At the start of the program it instantiates all beans, and only once. – Impulse The Fox Mar 20 '18 at 07:59
  • I mean constructor of an object which is called when bean is created. Why in provided link which has +280 score is information that is possible? – ByeBye Mar 20 '18 at 08:01
  • The links _tells_ you @ByeBye. Passivation and proxying. – Boris the Spider Mar 20 '18 at 08:05