我正在学习spring和做一些研发工作。
我尝试了“依赖”的概念。
<bean id='example1' class='com.freelancing.SpringExample.Example1'
depends-on="example">
<!-- <property name="personExample"> <value>sparsh</value> </property> -->
<property name="age">
<value>25</value>
</property>
<property name="listVariable">
<list>
<value>3434</value>
<value>3432423</value>
<value>34324324</value>
</list>
</property>
<property name="setVariable">
<set>
<value>45</value>
<value>45</value>
<value>23432</value>
</set>
</property>
</bean>
<bean id='example' class='com.freelancing.SpringExample.Example'>
<!-- <constructor-arg index='0'> <value>2345</value> </constructor-arg>
<constructor-arg index='1'> <value>sparsh</value> </constructor-arg> -->
<property name="roll">
<list>
<value>2</value>
<value>3</value>
<value>5</value>
</list>
</property>
<property name="salary">
<value>12345</value>
</property>
<property name='uname'>
<value>nane</value>
</property>
<property name="ex1" ref="example1"></property>
</bean>现在,在这段代码中,您可以清楚地看到,我故意使Example1类依赖于示例。但在示例bean中,它需要Example1 obj。这是一种循环dependency.But,它没有给我这个错误。
请帮我解释一下。
发布于 2015-09-13 00:12:09
当您在属性中使用循环依赖项时,Spring可以解析它们。在本例中,它可以首先创建一个example (因为example1依赖于它),然后创建一个example1,然后将example1设置到example对象的"ex1“字段中。
当然,如果您需要在构造函数中使用example1,这将不起作用。这就是我个人更喜欢构造函数注入的原因,因为它从一开始就防止了循环依赖(它们往往是糟糕代码的标志)。
因此,通过getter方法(或@Autowired)的注入允许spring解决循环依赖,但如果你问我,这并不一定是一件好事,它只是掩盖了一些代码不好的事实。
https://stackoverflow.com/questions/32540892
复制相似问题