Skip to content
Advertisement

Should we use Spring @Bean with static method?

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();
    }

}

Answer

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.

Advertisement