I have come across some java classes used in the spring framework. First, there is the beans in the applicationContext.xml
<bean id="someBean" parent="txProxyTemplate">
<property name="target">
<bean class="path.to.bean.impl.SomeBeanImpl">
...
</bean>
...
</bean>
And I have the interface ISomeBean, and its implementation SomeBeanImpl
Then, I have another class which uses ISomeBean.
public class SomeOtherClass {
...
public function doStuff() {
...
ApplicationContext ctx;
SomeBean theBean = (SomeBean) ctx.getBean;
}
}
I want to know why do we cast to an interface instead of casting to the class.
Why would you want to tie SomeOtherClass to a specific implementation? Using the interface, you get loose coupling - you can test against a fake implementation, or switch to a different implementation later.
This is a large part of the benefit of inversion of control - you aren't as tightly coupled to your dependencies as if you instantiate them directly within the class.
The logic behind such type of casting is to give freedom to the Spring IOC and Dependency Injection. One of the benefits of using this approach is that the coupling between classes is very loose,
for example in ur case if some fine morning u decide to change the code of ISomeBeanImpl, u don't need to change anything else as long as functionality doesn't change..
Have a look on Spring IOC documentation, the idea will be more clear...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With