Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the problem of Java circular dependency

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to solve the problem of Java circular dependency. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

Recently, I saw a problem: if there are two classes An and BMague A, there is an object of B in Class B, and there is an object an of A. in Class B, then how to solve the interdependence between these two classes? in a few days, I will tell you about the circular dependency of Java, raksmart server.

Take a chestnut 1:

You can see that in the constructor of class A, an object of B is new, while in the constructor of class B, an object of An is new.

If we run this class at this time, the following error will be reported:

Exception in thread "main" java.lang.StackOverflowError

The cause of the problem is that there is a circular dependency between class An and class B.

So is there a way to solve this problem? The answer is: yes

Take Chestnut 2:

Run example 2, and the result is as follows:

BB

AA

AA

BB

In example 2, testa and testb are created with default constructors for classes An and B, creating instances of classes An and B.

Then inject an instance of B into class A. Testa.b = testb

Inject an instance of An into class B. Testb.a = testa

Testa.print () calls b.printA (); b.printA () calls a.printA (); a.printA () displays the result as AA

Through the method of attribute injection, we make class An and class B no longer appear the errors in example 1, and make the two interdependent classes An and B can call interdependent methods.

In fact, spring also solves the problem of class interdependence through dependency injection.

After reading the above, do you have any further understanding of how to solve the problem of Java circular dependency? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report