在所有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,并且更改设计,逻辑和业务需要一个漫长的过程来要求由以下人员来完成:其他团队。


慕沐林林
浏览 154回答 3
3回答

慕妹3146593

Spring上下文完全初始化后,您将必须订阅ContextRefreshedEvent事件才能执行代码。@Componentclass N51348516 implements ApplicationListener<ContextRefreshedEvent> {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void onApplicationEvent(ContextRefreshedEvent event) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(event.getApplicationContext());&nbsp; &nbsp; }}但是我想您真正需要的是使用@Lazy注释使bean变得懒惰,以便您能够正确访问它们。

炎炎设计

我不明白为什么您首先需要使用serviceDispatcher。你可以尝试直接注入BeanB到BeanA:@Servicepublic class BeanA{&nbsp; &nbsp;private BeanB beanB;&nbsp; &nbsp;@Autowired&nbsp; &nbsp;public BeanA(BeanB b){&nbsp; &nbsp; &nbsp; beanB = b;&nbsp; &nbsp; &nbsp; beanB.someMethod();&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java