Rupesh
Rupesh

Reputation: 2667

Why use init-method property if the same thing could be done in the constructor?

I am bit confused about usability of the init-method property. Can anybody provide me with a use case where doing something in the constructor will not make sense and init-method property would be good fit?

As per my understanding one would be using init-method property while defining bean if on bean creation some task needs to be performed but this can be done in bean's constructor as well.

Upvotes: 2

Views: 65

Answers (2)

Mureinik
Mureinik

Reputation: 311978

There are several use-cases for init-method. The most important is when the class initialization logic requires several properties to be set, but they cannot be set via the constructor. In this case, the flow would be:

  1. Construct the bean (default constructor)
  2. Inject the properties via setter methods
  3. Run the init method

Another useful case for init-method is when modernizing legacy code. Some classes in old code bases simply have these methods, for whatever good or bad reason. Instead of forcing you to rewrite the code, Spring offers you an easy way to consume it.

Upvotes: 2

vrudkovsk
vrudkovsk

Reputation: 363

I guess all injections made via properties are in place when init is called.

Upvotes: 1

Related Questions