4

I am learning Spring, and the book I am reading has the following code line

@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

Why is it needed the static keyword, is it normal to declare the @Bean annotation on static methods, if it is, why ?

Zong
  • 6,160
  • 5
  • 32
  • 46
tt0686
  • 1,771
  • 6
  • 31
  • 60
  • [This question](https://stackoverflow.com/questions/17193365/what-in-the-world-are-spring-beans) might help. – Turing85 Jun 30 '18 at 16:03
  • 1
    It's needed for that *specific* type because the "placeholder" system is what's used to fill in expressions like `${server.port}`. It's used in bootstrapping the entire configuration and so has to be available before everything gets going. – chrylis -cautiouslyoptimistic- Jun 30 '18 at 16:13
  • 1
    Consider also other sources of truth, beside the book you are reading, like the spring official reference documentation - https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-factory-placeholderconfigurer – hovanessyan Jun 30 '18 at 17:00

1 Answers1

3

The PropertySourcesPlaceholderConfigurer object is a BeanFactoryPostProcessor, so, according to the Spring documentation:

Special consideration must be taken for @Bean methods that return Spring BeanFactoryPostProcessor (BFPP) types. Because BFPP objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as @Autowired, @Value, and @PostConstruct within @Configuration classes. To avoid these lifecycle issues, mark BFPP-returning @Bean methods as static.

By marking this method as static, it can be invoked without causing instantiation of its declaring @Configuration class, thus avoiding the above-mentioned lifecycle conflicts. Note however that static @Bean methods will not be enhanced for scoping and AOP semantics as mentioned above. This works out in BFPP cases, as they are not typically referenced by other @Bean methods. As a reminder, a WARN-level log message will be issued for any non-static @Bean methods having a return type assignable to BeanFactoryPostProcessor.

Robert Hume
  • 1,129
  • 2
  • 14
  • 25