yapkm01
yapkm01

Reputation: 3773

Spring - why initialization is called after setter method

Just curious.

  1. Why bean initialization is done after setter's method? I thought initialization is best done before setter method - like doing validation to ensure it's good prior to setting the value to the instance member

  2. Why beanPostProcessor considered a after initialization when it has a beforeInitialization method?

Upvotes: 1

Views: 1471

Answers (2)

Adrian Shum
Adrian Shum

Reputation: 40036

  1. From my understanding, calls of setters etc is considered to be the action to setup the initial state of the bean. You cannot do any meaningful initialization without the initial state of the bean set. Just think what will happen if initialization is done before setters: (assume we are using setter injection, not ctor injection) The bean is created by calling the default ctor, and then you call the initialization, what can you initialize then? The bean is simply a blank object without dependencies properly injected. If you can do initialization in such case, such kind of initialization can be simply put in your ctor.

  2. For BeanPostProcessor, I believe the "post" is not referring to post-initialize. It is simply for you to do post processing after the bean is created (i.e. post-creation). As it is common to do such kind of post processing in two different timing, which is before and after the bean is initialized. Hence for the two methods.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160201

  1. So initialization can use the values set on the bean.
  2. Because it's a post-processor.

Upvotes: 1

Related Questions