2

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?

Jakov
  • 879
  • 2
  • 17
  • 36
  • 1
    Spring classes are singletons by default so there is only 1 instance, it makes no difference, it is effectively static without the static keyword. The actual class spring uses will be a proxy around the class you have specified. – Essex Boy Nov 05 '20 at 13:43
  • 1
    @EssexBoy it makes a world of difference. A `static` method cannot access instance variables, which are often used in `@PostConstruct` methods. Also it would lead to issues if a bean would have a scope like request or session as `static` would be on class level and not on instance level. – M. Deinum Nov 05 '20 at 13:45

2 Answers2

5

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.

sgtcortez
  • 407
  • 4
  • 15
  • Note: PostConstruct will not always is calling after the constructor. PostConstruct can be called without calling bean constructor. E.g. when we add the same bean to application context but with another qualifier name. In this case constructor will be called once while PostConstruct multiple times. – Maksym Jul 29 '21 at 13:12
  • @MaksymPecheniuk "PostConstruct will not always is calling after the constructor. PostConstruct can be called without calling bean constructor." - That does not make sense. It isn't possible to call a `PostConstruct` method (or any other instance method) on an object before it is constructed. – Jeff Scott Brown Jul 29 '21 at 14:14
  • Sorry, my fault for bad description. Constructor is called first for sure. But it is possible that constructor will be called once while postConstruct will be called multiple times. – Maksym Jul 29 '21 at 14:47
3

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.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47