为什么在spring中在控制层注入业务层要定义为接口

例如:

@RestController
public class UserController {
	
	@Autowired
	private UserService userService;
...
	}

(UserService 的实现类是UserServiceImpl)

那么如果写成下面这样行不行呢?

@RestController
public class UserController {
	
	@Autowired
	private UserServiceImpl userServiceImpl;

...
	}
	

答案是不行的。

因为spring在实例化 UserServiceImpl 后,指定该实例对象的类型是它的接口。

类似的解释请看这个博客
https://blog.csdn.net/ligeforrent/article/details/76033083

猜你喜欢

转载自blog.csdn.net/qq_27263265/article/details/82876385