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

Viewed 1847

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?

2 Answers

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.

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

A method marked with @PostConstruct is a method that Spring is supposed to invoke after creating the bean instance. The method is generally used to do some post construction configuration of the instance. It would make no sense for that method to be static because a static method may not interact with any instance state in any instances of the class.

Related