Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot with Kotlin: init block vs @PostConstruct annotation

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.

like image 221
tonnoz Avatar asked Sep 08 '25 16:09

tonnoz


2 Answers

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.

like image 81
Simon Martinelli Avatar answered Sep 10 '25 05:09

Simon Martinelli


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.

like image 36
Kent Avatar answered Sep 10 '25 06:09

Kent