springboot中 @Autowired 注入父类,为什么实际是子类实例

springboot中 @Autowired 注入父类,为什么实际是子类实例

看见你的问题我赶紧去试了一下

img


img


img


所有可能都试了一下发现子类加了@Component这个注解才能注入DogTestService这个类,而如果TestService加了@Component注解的话spring会直接注入TestService对象。

img


当这个父类没有@Component注解并且有多个继承子类时子类@Component需要赋值value属性。controller需要用@Resource(name = "cat")注解来实现不同子类的注入

img