Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

MAYUR KUMBHAR
MAYUR KUMBHAR

Posted on

     

Circular ⭕ dependency exceptions in Spring❗

Issue?

When two beans are waiting for each other to be created in the spring context so that autowiring can happen, this state is called asCircular Dependency and we get theBeanCurrentlyInCreationException exception.

Scenario, lets say BeanA is defined as below

@ComponentclassBeanA{@Autowired// here BeanA is depends on BeanBpublicBeanBbean;}
Enter fullscreen modeExit fullscreen mode

Now lets say we have BeanB as below

@ComponentclassBeanB{@Autowired// here BeanB is depending on BeanApublicBeanAbean;}
Enter fullscreen modeExit fullscreen mode

So there is dependency between two components resulting in circular dependency as each bean is waiting for its dependent bean to created for autowiring.

Solution

Developer should be careful while creating the Beans, making sure there are no circular dependency. But is worst case if there exists case or by mistake some developer put the circular dependency then we can follow below to resolve this.

Use setter injection instead of constructor injection

We can use the setter injection in one of class for dependent bean, so that injection is happed after one object is created avoiding the race condition.

Use Lazy initialization on beans

We can use@Lazy annotation on one of the bean in circular dependency so that one of bean creation is delayed until bean is actually required.

Refactor code to remove circular dependency

We should avoid creating such circular dependency in first place, and refactor code respectively to remove the circular dependency.


Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

  • Location
    India
  • Joined

More fromMAYUR KUMBHAR

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp