IoC, DI
✅ Inversion of Control
- control flow is inversed from programmer to ➡️ external source(ex:
framework) Frameworkwill call my code, not the programmer- 👎🏻 Before IoC
- programmer explicitly codes what class will be used in
Service client code Service client codeknows 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 codedoes 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,implementsimport
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 }
OrderServiceImpldepends onOrderService,MemberRepository,DiscountPolicyMemberRepository,DiscountPolicyis 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
orderServiceis created, return conrete classnew OrderServiceImpl - when
OrderServiceImplis created, create conrete classMemoryMemberRepositoryandRateDiscountPolicy
- when AppConfig is run and
✅ IoC, DI container
- tool that helps
create objectandhandle, connect dependencies - tool to help
IoCandDI- ex)
AppConfigis an example ofIoC, DI container AppConfighandlesDIforOrderService
- ex)
✅
✅
✅
✅
✅
✅
✅
This post is licensed under CC BY 4.0 by the author.