Spring setter dependency injection after all beans have been created

夙愿已清 提交于 2019-12-06 07:31:42

If you're creating the beans in an ApplicationContext, the ApplicationContext fires ApplicationEvents to any registered ApplicationListener callbacks. One of those should tell you when all the beans in the context are wired together via Spring.

Here's what the documentation says about circular dependencies:

If you use predominantly constructor injection, it is possible to create an unresolvable circular dependency scenario.

For example: Class A requires an instance of class B through constructor injection, and class B requires an instance of class A through constructor injection. If you configure beans for classes A and B to be injected into each other, the Spring IoC container detects this circular reference at runtime, and throws a BeanCurrentlyInCreationException.

One possible solution is to edit the source code of some classes to be configured by setters rather than constructors. Alternatively, avoid constructor injection and use setter injection only. In other words, although it is not recommended, you can configure circular dependencies with setter injection.

Unlike the typical case (with no circular dependencies), a circular dependency between bean A and bean B forces one of the beans to be injected into the other prior to being fully initialized itself (a classic chicken/egg scenario).

I would just use setter injection in this case, or try to avoid the circular dependency in the first place. Another solution is to make one of the beans BeanFactoryAware, and to lookup the other bean from the bean factory when the reference is needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!