What is dependency management in Spring?
Lets consider the following interfaces and concrete class that implements interface.
Lets consider a spring implementation:
Ref:
http://www.mkyong.com/spring/spring-loosely-coupled-example/
Lets consider the following interfaces and concrete class that implements interface.
public interface IOutputGenerator
{
public void generateOutput();
}
public class CsvOutputGenerator implements IOutputGenerator
{
public void generateOutput(){
System.out.println("Csv Output Generator");
}
}
public class JsonOutputGenerator implements IOutputGenerator
{
public void generateOutput(){
System.out.println("Json Output Generator");
}
}
Lets call it directly.
public class App
{
public static void main( String[] args )
{
IOutputGenerator output = new CsvOutputGenerator();
output.generateOutput();
}
}
In this way, the problem is the “output” is coupled tightly to
CsvOutputGenerator, every change of output generator may involve code
change. If this code is scattered all over of your project, every change
of the output generator will make you suffer seriously.
Lets consider a spring implementation:
public class OutputHelper
{
IOutputGenerator outputGenerator;
public void generateOutput(){
outputGenerator.generateOutput();
}
public void setOutputGenerator(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator;
}
}
<!-- Spring-Common.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="OutputHelper" class="com.subash.output.OutputHelper">
<property name="outputGenerator" ref="CsvOutputGenerator" />
</bean>
<bean id="CsvOutputGenerator" class="com.subash.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.subash.output.impl.JsonOutputGenerator" />
</beans>
public class App
{
public static void main( String[] args )
{
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-Common.xml");
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");
output.generateOutput();
}
}
Now, you just need to change the Spring XML file for a different output
generator. When output changed, you need to modify the Spring XML file
only, no code changed, means less error.With Spring framework – Dependency Injection (DI) is a useful feature
for object dependencies management, it is just elegant, highly flexible
and facilitates maintainability, especially in large Java project.Ref:
http://www.mkyong.com/spring/spring-loosely-coupled-example/
Comments
Post a Comment