java - 有没有办法在所有spring上下文初始化后调用bean中的方法
问题描述
我有一个问题,这是它的要点:(循环中涉及更多的类,但它可以用这种方式表示)
@service
public class serviceDispatcher{
@Autowired
private BeanA a;
@Autowired
private BeanB b;
public BeanA getBeanA(){
return a;
}
public BeanB getBeanB(){
return b;
}
}
@Service
public class BeanA{
@Autowired
ServiceDispatcher sd;
@PostConstruct
private void init(){
sd.getBeanB().method;
}
}
所以很明显我得到一个空指针,因为 BeanB b 尚未解决。我也使用了 afterPropertiesSet ,它是一样的。我的问题是,是否有办法在整个上下文初始化后运行 init() 方法,这样我就不会得到这个空指针?我知道这种循环依赖很麻烦,需要解决,但我只是重构一个巨大的项目以使用 Spring DI 并更改设计、逻辑和业务需要一个漫长的过程来要求它完成其他球队。
解决方案
一旦弹簧上下文完全初始化,您将必须订阅ContextRefreshedEvent事件才能执行您的代码。
@Component
class N51348516 implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println(event.getApplicationContext());
}
}
但我想您真正需要的是使用@Lazy注释使您的 bean 变得懒惰,以便您能够正确访问它们。
推荐阅读
- c++ - clang-format -style=文件在 Ubuntu 18.04 中不起作用
- python - 如何在海龟中独立移动 2 个对象?
- c# - 如何在 Unity with Vuforia 中使用我自己的 AI 模型进行图像识别?
- wso2 - WSO2 APIM 为 API 的后端服务器添加序列
- amazon-web-services - 如何在部署时将值传递给 AWS CDK?
- solr - 计算涵盖的查询词数除以 solr 中的查询词数
- r - 创建 Tibble 表时出现未使用的参数错误
- python - A Level Space 入侵者项目问题
- javascript - 如何将这些按钮的效果更改为选择以便删除按钮?
- java - 如何将字符串转换为二维数组(java)(GameBoard)