我有一个问题,这是它的要点:(循环中涉及更多类,但是可以用这种方式表示)@servicepublic class serviceDispatcher{ @Autowired private BeanA a; @Autowired private BeanB b; public BeanA getBeanA(){ return a; } public BeanB getBeanB(){ return b; }}@Servicepublic class BeanA{ @Autowired ServiceDispatcher sd; @PostConstruct private void init(){ sd.getBeanB().method; }}所以很明显我得到了一个空指针,因为BeanB b尚未解析。我还使用了afterPropertiesSet,它是相同的。我的问题是,是否有一种方法可以在初始化整个上下文之后运行init()方法,以便不获取此空指针?我知道一个事实,即存在这种循环依赖关系很麻烦,需要解决,但我只是重构一个大型项目以使用Spring DI,并且更改设计,逻辑和业务需要一个漫长的过程来要求由以下人员来完成:其他团队。
3 回答
![?](http://img1.sycdn.imooc.com/533e4d660001312002000200-100-100.jpg)
慕妹3146593
TA贡献1820条经验 获得超9个赞
Spring上下文完全初始化后,您将必须订阅ContextRefreshedEvent事件才能执行代码。
@Component
class N51348516 implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println(event.getApplicationContext());
}
}
但是我想您真正需要的是使用@Lazy注释使bean变得懒惰,以便您能够正确访问它们。
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
炎炎设计
TA贡献1808条经验 获得超4个赞
我不明白为什么您首先需要使用serviceDispatcher。你可以尝试直接注入BeanB到BeanA:
@Service
public class BeanA{
private BeanB beanB;
@Autowired
public BeanA(BeanB b){
beanB = b;
beanB.someMethod();
}
}
添加回答
举报
0/150
提交
取消