
本文旨在解释 Spring 框架中 @PostConstruct 注解在某些情况下会被执行两次的原因,并提供相应的解决方案。通常,这种情况是由于创建了多个 Spring 上下文导致的。理解 Spring 上下文的生命周期以及 Bean 的作用域是解决此问题的关键。
在 Spring 应用中,ApplicationContext 是一个核心概念,它负责管理 Bean 的生命周期,包括 Bean 的创建、初始化、销毁等。 当我们使用 @PostConstruct 注解时,Spring 会在 Bean 初始化完成后调用被注解的方法。
问题中出现的 @PostConstruct 方法执行两次的根本原因在于创建了两个独立的 Spring 上下文:
由于每个 Spring 上下文都独立管理自己的 Bean,因此 MyCache Bean 会在每个上下文中被创建一次,导致 @PostConstruct 方法被调用两次。
避免 @PostConstruct 执行两次的关键在于确保只存在一个 Spring 上下文,或者至少确保只在一个上下文中创建和管理 MyCache Bean。 以下是一些常见的解决方案:
这是最直接的解决方案。 TextFilter 类不需要手动创建 AnnotationConfigApplicationContext。 可以通过 Spring 的依赖注入机制,将 MyCache Bean 注入到 TextFilter 类中。
@Component // 将 TextFilter 纳入 Spring 管理
public class TextFilter {
@Autowired // 自动注入 MyCache Bean
private MyCache<MyData> cache;
public String filter(String originalText) {
return this.cache.get().filter(originalText);
}
}注意事项:
如果确实需要在 TextFilter 中使用手动创建的 AnnotationConfigApplicationContext,需要确保 MyCache Bean 只在一个上下文中定义。 可以将 MyCache 的定义从 AppConfig 移除,只在手动创建的上下文中定义。
public class TextFilter {
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
private MyCache<MyData> cache;
public TextFilter() {
this.context.scan("com.sensitive_words.utils");
// 在 TextFilter 的上下文中注册 MyCache
this.context.register(MyCache.class);
this.context.refresh();
this.cache = this.context.getBean(MyCache.class);
}
public String filter(String originalText) {
return this.cache.get().filter(originalText);
}
}并且从 AppConfig 中移除 MyCache 的 Bean 定义:
@Configuration
@EnableScheduling
public class AppConfig {
// 移除 MyCache 的 Bean 定义
// @Bean
// public MyCache<MyData> myCache() {
// return new MyCache<MyData>();
// }
}注意事项:
如果需要每次都创建一个新的 MyCache 实例,可以将 Bean 的作用域设置为 prototype。
@Configuration
@EnableScheduling
public class AppConfig {
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public MyCache<MyData> myCache() {
return new MyCache<MyData>();
}
}注意事项:
@PostConstruct 方法被执行多次通常是由于创建了多个 Spring 上下文导致的。 解决此问题的关键在于确保 Bean 只在一个上下文中被创建和管理。 移除手动创建的 Spring 上下文,或者使用 Spring 的依赖注入机制是推荐的解决方案。 在选择解决方案时,需要根据具体的应用场景和需求进行权衡。
以上就是Spring 中 @PostConstruct 注解执行两次的原因及解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号