我们应该在静态方法中使用 Spring @Bean 吗?
Should we use Spring @Bean with static method?
这是将@Bean 与静态方法一起使用的好习惯吗?
public class Foo {
}
@Configuration
public FooFactory {
@Bean
public static Foo getFoo() {
return new Foo();
}
}
一般来说,@Bean
方法不需要是静态的。
当 @Bean
方法不是静态的时,创建 bean 需要首先创建它的 class、FooFactory
的实例。绝大多数情况下这很好,但如果 bean 属于应用程序上下文生命周期早期所需的类型,有时会导致问题。这种类型的两个例子是 BeanPostProcessor
和 BeanFactoryPostProcessor
。在这些情况下,您应该将 @Bean
方法声明为静态的,以允许在不首先创建 @Configuration
class.
实例的情况下创建 bean
您可以在 Spring Framework 的参考文档中的 this section 末尾了解更多相关信息:
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.
这是将@Bean 与静态方法一起使用的好习惯吗?
public class Foo {
}
@Configuration
public FooFactory {
@Bean
public static Foo getFoo() {
return new Foo();
}
}
一般来说,@Bean
方法不需要是静态的。
当 @Bean
方法不是静态的时,创建 bean 需要首先创建它的 class、FooFactory
的实例。绝大多数情况下这很好,但如果 bean 属于应用程序上下文生命周期早期所需的类型,有时会导致问题。这种类型的两个例子是 BeanPostProcessor
和 BeanFactoryPostProcessor
。在这些情况下,您应该将 @Bean
方法声明为静态的,以允许在不首先创建 @Configuration
class.
您可以在 Spring Framework 的参考文档中的 this section 末尾了解更多相关信息:
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 typeBeanFactoryPostProcessor
orBeanPostProcessor
), 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.