Spring setter dependency injection after all beans have been created

余生长醉 提交于 2019-12-22 12:27:13

问题


I have a set of Spring beans created using constructor injection. Since there are (by design) circular references to other beans, I'd like to post-process the beans once they are all created to inject the references to other beans.

Initial attempts at using BeanPostProcessor show that the BeanPostProcessor is running after EACH bean is instantiated, not waiting until all have been instantiated.

Does Spring provide a mechanism for post-processing as set of beans after all have been created?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11655530/spring-setter-dependency-injection-after-all-beans-have-been-created

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