Home > database >  Spring Boot with Kotlin: init block vs @PostConstruct annotation
Spring Boot with Kotlin: init block vs @PostConstruct annotation

Time:10-25

In a Spring Boot application written in Kotlin it is possible to use both the init block or the @PostConstruct JSR-250 lifecycle annotation to do something right after instantiation. What are the consequences of using one vs the other in a @Component ? Can there be any behavioral difference?

Similar question here.

CodePudding user response:

As you said:

do something right after instantiation.

init block gets executed during the instantiation. Therefore, the postconstruct annotation would be the right way to go, no matter whether you have injected beans or not.

CodePudding user response:

An init block is pure Kotlin and has nothing to do with Spring.

@PostConstruct is a way to initialize after the Bean has been created an all dependencies are injected.

So if you want to access injected beans, you MUST use @PostConstruct.

For all other cases, you can use the init block or a constructor.

  • Related