What is a right way to initialize fields in Spring Beans?

Assuming the value is a constant, the first option is the simplest to understand and works without Spring, simplifying unit testing.

The second and fourth option are more complex and introduce an unnecessary dependency on the Spring container without any benefit. The third option is outright bizarre, since you're using @Autowired and not performing dependency injection.


I believe spring offers all those options because you might run into different requirements...

  1. If you want MAX_INT and there's no way on earth anyone needs to initialize it differently, then it's enough to declare int field = Integer.MAX_INT regardless of Spring.

  2. If you do want to allow other initial configurations, then you can initialize it using @Autowired, or through a constructor arg, or setter/getter... it's a matter of taste.

  3. @PostConstruct is more suitable for complex situations, e.g. if your field needs to be calculated based on other injected fields.