Thursday, March 15, 2012

Just Spring reading notes

Today I started reading about Spring.
Dependency Injection (inversion of control)
Provides dependency to your objects at runtime.

Here is the problem:
class DataReaderClient{
FileReader fileReader=new FilerReader();
fileReader.read();

}

in this code, client and reader are tightly coupled together.
improve to:
designing to interfaces
Interface Ireader{
read();
}

class DataReaderClient{
Ireader fileReader=new FilerReader();
fileReader.read();

}

but this is still hardwired, the client has to know which concrete implementation to use.

Spring is to remove this kind of dependency.It works on one single mantra:DI.
When a standalone program starts, it starts the program,creates dependencies,then proceeds to execute the appropriate methods. All dependencies and relationship are created by IoC container and they are injected into the main program as properties.

class DataReaderClient{
Ireader reader=null;
ApplicationContext ctx = null;

public DataReaderClient(){
ctx = new ClassPathXmlApplicationContext("ssss.xml");
}

fetchData(){
reader = (IReader)ctx.getBean("reader");
reader.read();
}
}

sss.xml




------
client will always have to inject a type of IReader, can improve to a service layer

class DataReaderClient{
ReaderService service=null;
ApplicationContext ctx = null;

public DataReaderClient(){
ctx = new ClassPathXmlApplicationContext("ssss.xml");
service = ctx.getBean("readerService");
}

fetchData(){
reader = (IReader)ctx.getBean("reader");
reader.read();
}
}


No comments:

Post a Comment