1.

What Is a Circular Dependency?

Answer»

Circular Dependency in Spring is a situation when a bean depends on another bean, but at the same time, the other bean depends on the first one in turn.

Now when the Spring context is trying to load all the beans, it tries to create beans in the order needed for them to work COMPLETELY. For EXAMPLE, if we have an application with three beans where bean X depends on bean Y and it depends on bean Z. Spring will create beans in a sequence where bean Z is first created, then create Y with Z been injected to it and FINALLY create X with Y being injected into it.

bean X > bean Y > bean Z

But, in case we have a circular dependency, where bean X depends on bean Y; but Y, in turn, depends on X again.

bean X > bean Y > bean X

Here Spring is unable to determine which bean should be created first since they depend on one another. In this case, Spring will throw a BeanCurrentlyInCreationException while loading the Application context. It can happen if dependencies are not defined properly while using CONSTRUCTOR injection as it requires to create and load all the dependencies while loading the context.

Workarounds:

  1. Redesign:

An appropriate redesign of the components in a manner that their hierarchy is well designed can avoid circular dependencies.

  1. Use @Lazy:
@Autowired     public X (@Lazy Y y) {         this.y = y; }
  1. Use Setter/Field Injection:

As setter-based injection loads the dependencies only when required; can help in avoiding error due to a circular dependency.

    @Autowired     public VOID setY (Y y) {         this.y = y; }


Discussion

No Comment Found