我遇到了一些在 spring 框架中使用的 java 类。首先,applicationContext.xml 中有 bean
<bean id="someBean" parent="txProxyTemplate">
<property name="target">
<bean class="path.to.bean.impl.SomeBeanImpl">
...
</bean>
...
</bean>
Run Code Online (Sandbox Code Playgroud)
我有接口ISomeBean和它的实现SomeBeanImpl
然后,我有另一个使用 ISomeBean 的类。
public class SomeOtherClass {
...
public function doStuff() {
...
ApplicationContext ctx;
SomeBean theBean = (SomeBean) ctx.getBean;
}
}
Run Code Online (Sandbox Code Playgroud)
我想知道为什么我们要转换到接口而不是转换到类。
为什么要绑定SomeOtherClass到特定的实现?使用该接口,您会获得松散耦合 - 您可以针对假实现进行测试,或者稍后切换到不同的实现。
这是控制反转的很大一部分好处 - 您与依赖项的耦合不像直接在类中实例化它们那样紧密。
| 归档时间: |
|
| 查看次数: |
1671 次 |
| 最近记录: |