Circular Dependencies in Spring

Pradeesh Kumar
3 min readNov 4, 2020

--

Image by Spring Framework

Spring is one of the most elegant frameworks that’s used by most Java enterprise application developers. It has made the life of Java developers a lot easier. The fundamental functionality provided by the Spring Container is dependency injection.

During the design, there are various types of issues that we may face due to poor class designs or inappropriate use of associations. One of the common issues we see when we use dependency injection is the Circular dependency issue.

Overview of circular dependency

Circular dependency happens when two beans are dependent on each other during instantiation. Given below is a small example of a circular dependency in spring.

Example of circular dependency

In such situations, spring throws an exception as shown below.

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'Car': Requested bean is currently in creation: Is there an unresolvable circular reference?

How to fix the circular dependency in Spring?

1. Using setter injection

Using @Autowired at the setter method of the dependent bean instead of the constructor injunction solves the issue. In this case, Spring creates the beans, however, the dependencies are not injected until they are first used.

2. Using @Lazy at the injection point

A quick way to solve circular dependency is by adding @Lazy at the constructor injection point. It sets the dependency lazily. Spring uses a proxy instead of the real object at the injection point. This proxy delays the initialization of the underlying object until it is first used.

3. Using @PostContruct

@PostConstruct on a method will be invoked once the bean is instantiated. Using @Autowired on one of the beans and use a init method with @PostConstruct annotation. Init method will set the bean to the dependent bean.

4. Redesign

Circular dependency likely happens when the design is poor, wrong class hierarchies are followed, and improper associates are followed during the design. Resign the classes so that the problem is well separated.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Pradeesh Kumar
Pradeesh Kumar

Written by Pradeesh Kumar

Distributed Systems | Cloud Computing | Databases | Software Engineering

No responses yet

Write a response