a circular reference
- org.springframework.beans.factory.BeanCurrentlyInCreationException:
- Error creating bean with name 'AxxxxService':
- Bean with name 'BxxxxService'
- has been injected into other beans [CxxxxService] in its raw version as part of a circular reference,
- but has eventually been wrapped. This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching -
- consider using 'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.
复制代码 1)我在远程调用的api接口中的实现类里(ReiDetailApiImpl implements ReiDetailApi 这个类中使用了 ReiDetailService.selectByAdmin(id) 方法
什么是循环引用?
循环引用指的是两个或多个对象相互依靠,导致依靠关系形成一个闭环。在依靠注入框架中,如果A对象依靠于B对象,而B对象又依靠于A对象,就形成了循环引用。 (形成一个环)
- public class A {
- private B b;
- @Autowired
- public A(B b) {
- this.b = b;
- }
- }
- public class B {
- private A a;
- @Autowired
- public B(A a) {
- this.a = a;
- }
- }
复制代码 类A依靠于B,而类B依靠于A。这种环境会导致循环引用问题
解决循环引用
在Spring框架中,@Lazy 注解可以用来耽误加载一个bean,尤其是用来解决循环引用的问题。
通过将 @Lazy 应用于bean的注入,可以让Spring容器在创建bean时耽误对依靠的注入,从而避免在对象创建时直接解析和注入依靠,从而打破循环引用。
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Lazy;
- import org.springframework.stereotype.Service;
- import lombok.Data;
- @Data
- @Service
- public class AService {
- private BService bService;
- @Autowired
- public AService(@Lazy BService bService) {
- this.bService = bService;
- }
- public void performAction() {
- bService.doSomething();
- }
- }
- @Data
- @Service
- public class BService {
- private AService aService;
- @Autowired
- public BService(@Lazy AService aService) {
- this.aService = aService;
- }
- public void doSomething() {
- System.out.println("Doing something...");
- }
- }
复制代码- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Lazy;
- import org.springframework.stereotype.Service;
- import lombok.Data;
- @Data
- @Service
- public class AService {
- private BService bService;
- @Autowired
- public AService(@Lazy BService bService) {
- this.bService = bService;
- }
- public void performAction() {
- bService.doSomething();
- }
- }
- @Data
- @Service
- public class BService {
- private AService aService;
- @Autowired
- public BService(@Lazy AService aService) {
- this.aService = aService;
- }
- public void doSomething() {
- System.out.println("Doing something...");
- }
- }
复制代码 我在实际应用中
- @Resource
- @Lazy
- private MyTestService myTestService;//注入service
复制代码 @Lazy注解 用于耽误加载Bean,避免循环引用问题
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |