我正在学习 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类依赖于Example。但在Example bean中它需要Example1 obj。这是一种循环依赖。但它没有给我这个错误。
请帮我解释一下。
最佳答案
当您在属性中使用它们时,Spring 可以解决循环依赖问题。这种情况下,它可以先创建一个example
(因为example1依赖它),然后创建一个example1然后设置example1
进入 ex1
的字段“example
”对象。
当然,如果您需要构造函数中的 example1,则这将不起作用。这就是为什么我个人更喜欢构造函数注入(inject),因为它首先可以防止您出现循环依赖(它们往往是糟糕代码的标志)。
因此,通过 getter 方法(或 @ Autowired
)注入(inject)允许 spring 解决循环依赖,但如果你问我,这并不是一件好事,它只是隐藏了某些代码不好的事实。
关于java - Spring java中的“取决于”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540892/