java - Spring 静态方法

标签 java spring static

我正在学习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 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.

关于java - Spring 静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116433/

相关文章:

java - 如何从 View 模型更改 flowScope 对象?

C++:将静态类成员与静态类成员的传递版本进行比较

java - 测试时忽略 Spring Controller 上的 PreAuthorize 注释

java - Java "reference object"是否存在?

java - 是否有命令行工具告诉我特定类在哪个 JAR 中

java - 如何将项目从netbeans中的另一个类添加到列表框

java - 在 UsernamePasswordAuthenticationFilter 或 Controller 中创建 JWT token ?

c - 包括静态库和头文件Makefile问题(C)

java - 为什么我们不把所有东西都静态化呢?

java - 将 List<CustomerOrder> 分组到 Map<Gender, Money>