为了账号安全,请及时绑定邮箱和手机立即绑定

在所有spring上下文初始化之后,有没有办法在Bean中调用方法

在所有spring上下文初始化之后,有没有办法在Bean中调用方法

慕沐林林 2021-05-07 14:10:25
我有一个问题,这是它的要点:(循环中涉及更多类,但是可以用这种方式表示)@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 回答

?
慕妹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变得懒惰,以便您能够正确访问它们。


查看完整回答
反对 回复 2021-05-26
?
炎炎设计

TA贡献1808条经验 获得超4个赞

我不明白为什么您首先需要使用serviceDispatcher。你可以尝试直接注入BeanB到BeanA:


@Service

public class BeanA{

   private BeanB beanB;


   @Autowired

   public BeanA(BeanB b){

      beanB = b;

      beanB.someMethod();

   }

}


查看完整回答
反对 回复 2021-05-26
  • 3 回答
  • 0 关注
  • 153 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信