编写Controller时为什么只需注入接口?
来源:5-20 服务Controller的编写(1)

慕尼黑2548295
2020-08-24
老师您好,
编写Controller时为什么只需注入接口就可以使用之前编写过的与接口对应对Impl方法?这其中对原理是什么呢?
例如这里引入 IAdPlanService 接口
private final IAdPlanService adPlanService;
@Autowired
public AdPlanOPController(IAdPlanService adPlanService) {
this.adPlanService = adPlanService;
}
我们就可以直接使用编写过的对IAdPlanService的Impl来返回AdPlanResponse
@PostMapping("/create/adPlan")
public AdPlanResponse createAdPlan(@RequestBody AdPlanRequest request) throws AdException {
log.info("ad-sponsor: createAdPlan -> {}",
JSON.toJSONString(request));
return adPlanService.createAdPlan(request);
}
写回答
1回答
-
张勤一
2020-08-25
同学你好:
其实这就是 Spring 的 IOC(这个是 Spring 最大、也是最核心的特性),你需要好好的学习下,即使是接口,Spring 也是可以找到接口对应的实现类(实际是 Spring 容器中的 Bean),并完成自动注入的。
欢迎来 QQ 群随时交流、讨论,也非常感谢同学的支持!
10
相似问题