IoC, DI
✅ Inversion of Control
- control flow is inversed from programmer to ➡️ external source(ex:
framework
) Framework
will call my code, not the programmer- 👎🏻 Before IoC
- programmer explicitly codes what class will be used in
Service client code
Service client code
knows what concrete class it will use
1
2
3
4
5
public class OrderServiceImpl implements OrderService {
// private final DiscountPolicy discountPolicy = new FixDiscountPolicy();
private final DiscountPolicy discountPolicy = new RateDiscountPolicy();
}
- 👍🏻 After IoC
Service client code
does not know what concrete class will be used- controlled by
AppConfig
- control flow is inversed to
AppConfig
1
2
3
public class OrderServiceImpl implements OrderService {
private final DiscountPolicy discountPolicy; //no concrete class, only interface
}
1
2
3
4
5
6
public class AppConfig {
public OrderService orderService(){
return new OrderServiceImpl(new FixDiscountPolicy());
}
}
✅ Dependency Injection
Spring automatically gives one bean to another bean that needs it
- 👍🏻 OCP: can refrain from modifying service code, only has to modify config file
👍🏻 instead of creating object manually, you let Spring inject it
✔️ static DI: can see DI even without running code
extends
,implements
import
1 2 3 4 5 6 7 8 9
@Component public class OrderServiceImpl implements OrderService { private final MemberRepository repository; private final DiscountPolicy discountPolicy; @Autowired //constructor }
OrderServiceImpl
depends onOrderService
,MemberRepository
,DiscountPolicy
MemberRepository
,DiscountPolicy
is injected intoOrderServiceImpl
✔️ dynamic DI: check DI when code is run
1 2 3 4 5
public class AppConfig { public OrderService orderService(){ return new OrderServiceImpl(new MemoryMemberRepository(), new RateDiscountPolicy()); }
- when AppConfig is run and
orderService
is created, return conrete classnew OrderServiceImpl
- when
OrderServiceImpl
is created, create conrete classMemoryMemberRepository
andRateDiscountPolicy
- when AppConfig is run and
✅ IoC, DI container
- tool that helps
create object
andhandle, connect dependencies
- tool to help
IoC
andDI
- ex)
AppConfig
is an example ofIoC, DI container
AppConfig
handlesDI
forOrderService
- ex)
✅
✅
✅
✅
✅
✅
✅
This post is licensed under CC BY 4.0 by the author.