UrbanPro

Learn Java Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

How to handle Circular dependency in Spring?

Asked by Last Modified  

17 Answers

Learn Java

Follow 0
Answer

Please enter your answer

What I would like to do in this post is suggest 3 possible techniques for dealing with this problem. 1. Refactor your code This is probably the simplest and quickest way to fix this problem. Look at your code, analyse why your two beans are referencing one another. Is it absolutely necessary, can you...
read more
What I would like to do in this post is suggest 3 possible techniques for dealing with this problem. 1. Refactor your code This is probably the simplest and quickest way to fix this problem. Look at your code, analyse why your two beans are referencing one another. Is it absolutely necessary, can you re-write your code in such a way that only one bean need reference the other and vice-versa? Maybe consider creating a third bean that both other beans can be injected into which will perform the functionality that requires the different dependencies. If you have a growing number of circular dependency problems this may actually be indicative of deeper problems and point to overly-complex code, why not use this as an opportunity to step back, refactor your design and simplify your structure? Although refactoring can be the easiest way to fix this issue, it isn’t always the right answer. Maybe there’s no way you can easily remove the dependencies between the two beans and no sensible or pragmatic way you can create a third bean to fill this function. If this is the case then there are a couple of other ways you can work around this issue. 2. Extend ApplicationContextAware in your Bean(s) Step 2 is to make use of (or more specifically implement) Spring’s ApplicationContextAware interface in one of the beans causing your circular dependency problem. Implementing this interface will force you to provide a setter in your class for a Spring ApplicationContext. One of the neat things with this though, is that Spring will detect that your bean has implemented ApplicationContextAware and automatically inject a reference to the ApplicationContext into your bean without you having to manually configure injection of the property in your xml bean definition. Once you have setup your bean (say Bean1) as above, the next task is to stop injecting a reference to Bean2 into it. You can keep the setter method for Bean2 in Bean1 - we’ll make use of this in a minute - we just need to remove the reference to Bean2 from Bean1’s bean definition and thus remove the circular dependency problem. The last thing to do now is figure out how we’re going to get a reference to Bean2 from Bean1 because currently the Bean2 property in Bean1 is going to be null at application start-up. The way to do this is to look up Bean2 from the ApplicationContext programmatically at run-time. So using our current example, if Bean1 had a method that needed to call a function in Bean2 we could do something like: view plaincopy to clipboardprint? public class Bean1 implements ApplicationContextAware { ApplicationContext applicationContext; Bean2 bean2; public void doSomething() { if(bean2 == null) { this.setBean2((Bean2)this.applciationContext.getBean("bean2")); } bean2.callAnotherMethod(); } public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } public void setBean2(Bean2 bean2) { bean2 = bean2; } } Of course this is a simplified rendition and we’d probably want to add a load more error handling etc but hopefully it should illustrate this technique. Clearly it’s not the most elegant solution, but it is one that works and providing your code is well tested shouldn’t cause many problems. Where it starts to fall over however, is when you want to use references to Bean2 in more than one place in Bean1, or worse still if you have a number of beans that have circular reference problems. The above technique would still work in this situation, but you’d quickly find your code ballooning up in size and becoming very difficult to manage. So to counter this I offer a third possible solution to this problem, using a BeanPostProcessor. 3. Use a BeanPostProcessor The third strategy I describe here is actually one that I found first in a post on the Spring forum. This is essentially to create a bean that extends Spring’s BeanPostProcessor interface and use this to initialise any of the properties in beans that cannot be initialised using IoC due to circular dependancy problems. Rather than blog about (and attempt to claim any credit for) this in any great detail I shall instead just point you to the post on the Spring forum where I first encountered someone using technique. Summary I think the most elegant solution to this problem is where possible to refactor your code and remove any circular dependencies between your beans. Clearly however, this isn’t always possible and depending on the scenario either looking up one member of a circular dependency directly from the ApplicationContext or alternatively making use of the BeanPostProcessor technique should help to alleviate this problem. Either way, I hope this post has suggested some alternative methods that may be of use to you. read less
Comments

Spring container will take care of it.
Comments

MCA, BSC(H)(IT), 2 years diploma in advanced software Technology.

The circular dependency will cause the Spring Application Context to fail and the symptom is an error which indicate clearly about the problem
Comments

effective,result oriented teaching JAVA

you can use setter injection mechanism in any of the spring bean ...thats it
Comments

using of setters it will possible
Comments

Tutor taking Computer subjects Classes

Using of setters is recommended.
Comments

Java & .NET Trainer

using unique bean
Comments

Tutor

Using setters, instead of constructors, would resolve this issue, as the instantiation phase is done without adding dependencies.
Comments

Trainer

using setters
Comments

Industry expert and professional lecturer/trainer

Using setter dependency injection over constructor injection
Comments

View 15 more Answers

Related Questions

How do people become Java programmers?
Before you become a Java programmer, it's important that you earn an education and learn how to code using Java. While some programmers learn how to use Java on their own, you can learn it much faster...
Rishav
0 0
5
Which is a good Java training and placement institute for a fresher in Bangalore?
I know an institute in HYderabad which is giving 100% job guarantee or 100% fee refund. They have office in bangalore also, not sure whether they are offering this program in Bangalore. Please visit their...
Raja
0 0
5
How many years of experience should a good Java trainer need?
Minimum 4 years, actually it depends how much exposure you got and how you worked in project(s)
Nayan
0 0
5
What is the difference between checked and unchecked exceptions?
The main difference between checked and unchecked exception is that the checked exceptions are checked at compile-time while unchecked exceptions are checked at runtime
Wren
Anyone knows how to convert jsf primeface into bootstrap?
You already can use some bootstrap CSS classes and helpers but if you want give style to each UI control, you will need to set the primefaces theme to none.Then you will need to give some style to each...
Pradeep
1 0
9

Now ask question in any of the 1000+ Categories, and get Answers from Tutors and Trainers on UrbanPro.com

Ask a Question

Related Lessons

Java :: Inner Class Concepts
Java:: Inner Class Concepts--------------------------------- Inner class concepts introduced in Java v1.1 - as a part of AWT Event Handling improvements.When to use Inner class: - Without existing One...
M

Marimuthu P.

2 0
0

Example of DependsOnMethod in TestNG
public class dependsonM { @Test public void login() { System.out.println("login"); } @Test (dependsOnMethods = {"login"}) public void email() { //Intentionally I am failing this testcase Assert.assertTrue(false);...
S

Sarthak C.

0 0
0

Crux Of The Basic Interview Question Asked Around It Professionals
Question: Explain PSVM() in Java. Answer: This question is asked from a differnet persctive. Person asking this question is looking for deep java concepts. If answer in your mind is something like...


ListIterator Example
public class ListIteratorEx { public static void main(String args) { List<String> li = new ArrayList<String>(); li.add("java1"); li.add("java2"); li.add("java3"); li.add("java4"); ListIterator...
S

Sarthak C.

0 0
0

Recommended Articles

Java is the most commonly used popular programming language for the creation of web applications and platform today. Integrated Cloud Applications and Platform Services Oracle says, “Java developers worldwide has over 9 million and runs approximately 3 billion mobile phones”.  Right from its first implication as java 1.0...

Read full article >

Designed in a flexible and user-friendly demeanor, Java is the most commonly used programming language for the creation of web applications and platform. It allows developers to “write once, run anywhere” (WORA). It is general-purpose, a high-level programming language developed by Sun Microsystem. Initially known as an...

Read full article >

Before we start on the importance of learning JavaScript, let’s start with a short introduction on the topic. JavaScript is the most popular programming language in the world, precisely it is the language - for Computers, the Web, Servers, Smart Phone, Laptops, Mobiles, Tablets and more. And if you are a beginner or planning...

Read full article >

In the domain of Information Technology, there is always a lot to learn and implement. However, some technologies have a relatively higher demand than the rest of the others. So here are some popular IT courses for the present and upcoming future: Cloud Computing Cloud Computing is a computing technique which is used...

Read full article >

Looking for Java Training Classes?

Learn from the Best Tutors on UrbanPro

Are you a Tutor or Training Institute?

Join UrbanPro Today to find students near you
X

Looking for Java Training Classes?

The best tutors for Java Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Java Training with the Best Tutors

The best Tutors for Java Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more