首页 > 解决方案 > 有没有办法在所有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 并更改设计、逻辑和业务需要一个漫长的过程来要求它完成其他球队。

标签: javaspringdependency-injectionpostconstruct

解决方案


一旦弹簧上下文完全初始化,您将必须订阅ContextRefreshedEvent事件才能执行您的代码。

@Component
class N51348516 implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println(event.getApplicationContext());
    }
}

但我想您真正需要的是使用@Lazy注释使您的 bean 变得懒惰,以便您能够正确访问它们。


推荐阅读