Should we use Spring @Bean with static method?
Asked Answered
P

1

5

Is this a good practice to use @Bean with static method?

public class Foo {
}
@Configuration
public FooFactory {

    @Bean
    public static Foo getFoo() {
        return new Foo();
    }

}
Phenacaine answered 18/8, 2021 at 10:22 Comment(0)
C
9

Generally speaking, there's no need for @Bean methods to be static.

When a @Bean method is not static, creating the bean requires an instance of its class, FooFactory in your example, to be created first. The vast majority of the time this is fine, but it can sometimes cause a problem if the bean is of a type that is required very early in the application context's lifecycle. Two examples of such types are BeanPostProcessor and BeanFactoryPostProcessor. In these cases you should declare the @Bean method as static to allow the bean to be created without first creating an instance of your @Configuration class.

You can learn more about this at the end of this section in Spring Framework's reference documentation:

You may declare @Bean methods as static, allowing for them to be called without creating their containing configuration class as an instance. This makes particular sense when defining post-processor beans (for example, of type BeanFactoryPostProcessor or BeanPostProcessor), since such beans get initialized early in the container lifecycle and should avoid triggering other parts of the configuration at that point.

Calls to static @Bean methods never get intercepted by the container, not even within @Configuration classes (as described earlier in this section), due to technical limitations: CGLIB subclassing can override only non-static methods. As a consequence, a direct call to another @Bean method has standard Java semantics, resulting in an independent instance being returned straight from the factory method itself.

Conclude answered 18/8, 2021 at 12:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.