I know in spring we all code to interface. So the implementation class should not be known to outside world at all. But it is a public class so anyone make an instance of the implementation class also. How do you prevent this? Do you make the constructor private? Since spring creates an instance of through reflection, it should be fine. Has anybody put any thought on it? I know if you make an instance of the implementation class it will not work properly because dependencies are all null
, but that is beside the point.
views:
101answers:
3If you want only a single instance in the entire application you can use factory methods/singletons. The same method will be used by other classes referring to this class as well.
From http://static.springsource.org/spring/docs/2.0.x/reference/beans.html
3.2.3.2.2. Instantiation using a static factory method
<bean id="exampleBean"
class="examples.ExampleBean2"
factory-method="createInstance"/>
The purpose of Spring dependency injection is not just to hide the implementation class.
The main point is the you should not have to worry about which implementation class to use. We put the responsibility of providing the class to Spring's container.
The basic idea of the Dependency Injection is to have a separate object, an assembler, that populates a field in the lister class with an appropriate implementation for the finder interface.
See Martin Fowler for more.
I'm not sure, but I assume with Spring you can make an implementation class package-private rather than public. I know this is a good practice with Guice.