我正在学习Spring,正在看的书有如下代码行
@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
为什么需要static关键字,在静态方法上声明@Bean
注解是否正常,如果是,为什么?
最佳答案
PropertySourcesPlaceholderConfigurer
对象是一个 BeanFactoryPostProcessor
,因此,根据 Spring documentation :
Special consideration must be taken for
@Bean
methods that return SpringBeanFactoryPostProcessor
(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 asstatic
.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 toBeanFactoryPostProcessor
.
关于java - Spring 静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116433/