Search code examples
javaspringspring-bootpostconstruct

Spring: Why method annotated with @PostConstruct cannot be static?


I am reading documentation about @PostConstruct on this site: https://www.baeldung.com/spring-postconstruct-predestroy

It is written:

The method annotated with @PostConstruct can have any access level but it can't be static.

Can someone tell me why method annotated with this annotation cannot be static?


Solution

  • Well, the name of the method already says what it does.

    PostConstruct, this method will be called after the constructor. It can not be static because static methods can not access non static variables, methods and etc.

    If you need something static to be run once, you can use static blocks.