Spring Learning: IoC (Inversion of Control) and DI (Dependency Injection)
>
As the start, without the concept of Ioc and DI, here is what we can do
1. create a UserDao interface
public interface UserDao{
public void getUser();
}
2. Dao object implement interface
public class UserDaoImplA implements UserDao{
@Override
public void getUser(){
System.out.println("get user A data")
}
}
public class UserDaoImplB implements UserDao{
@Override
public void getUser(){
System.out.println("get user B data")
}
}
3. Create UserService interface
public interface UserService{
public void getUser();
}
4. Service object implement Service interface
public class UserServiceImplA implements UserService{
private UserDao userDao = new UserDaoImplA();
@Override
public void getUser(){
userDao.getUser();
}
}
public class UserServiceImplB implements UserService{
private UserDao userDao = new UserDaoImplB();
@Override
public void getUser(){
userDao.getUser();
}
}
@Test
public void test(){
UserService serviceA = new UserServiceImplA();
serviceA.getUser();
UserService serviceB = new UserServiceImplB();
serviceB.getUser();
}
It's not hard to see that if we wanted to create more User instance and need to update the code in service,
there'll be a lot of repetitive work.
The way to solve this issue is: using set in service and pass in the POJO object from outside, instead of creating
POJO object in service. The key logic change here is we no longder need to deal with creating object and can focus on
the development of service logic. This is the prototype of IoC logic.
public class UserServiceImpl implements UserService{
private UserDao userDao;
//using set
public void setUserDao (UserDao userDao){
this.userDao = userDao;
}
@Override
public void getUser(){
userDao.getUser();
}
}
@test
public void test(){
UserServiceImpl service = new UserServiceImpl();
service.setUserDao( new UserDaoImplA());
service.getUser();
service.setUserDao( new UserDaoImplV());
service.getUser();
}
What is IoC and DI?
IoC is a design principle that invert the control of object creation: According to the paper written by Martin Fowler,
instead of the programmer controlling the flow of a program, the external sources (framework, services or other components)
takes the control of it. Similar idea as we plug things into something.
DI is a design pattern which implements IoC principle. Implementations are plgged into object via constructors/setters/service lookups.
Here is Martin Flower's paper