关于@Autowired字段继承后能否被注入

Background

@Inherited是一种元注解(指的是修饰注解的注解)。注意:

@Inherited修饰的注解(例如@My)只有修饰在上,才会起到所谓的继承作用,修饰字段、方法是不能起到继承作用。
Java注解学习-@Inherited

关于@Autowired

举例说明。现在有父类FatherService,其有个字段TargetService@Autowired修饰;

@Service
public class FatherService {

    @Autowired
    public TargetService targetService;
}

子类SonService继承父类:

@Service
public class SonService extends FatherService{
    
}

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class SonServiceTest {

    @Autowired
    SonService sonService;

    @Test
    public void test() throws Exception {

        Assert.assertNotEquals(null, sonService.targetService);
    }
}

请问:测试类中的sonService.targetService是否为null
答案是不为null。原因是Spring的AutowiredAnnotationBeanPostProcessor.AutowiredFieldElement.inject会对一个类的本身的字段其所有父类的字段进行遍历,凡是含有@Autowired的字段都会被注入。我用反射方式来近乎实现这个结果:

SonService sonService = new SonService();
// 被注入的bean
TargetService ts = new TargetService(); 
// 获取对象的子类的父类的该字段
Field fatherField = sonService.getClass().getSuperclass().getDeclaredField("targetService");
// 注入
fatherField.set(sonService, ts);

为什么我在第一节提到了@Inherited?我原以为@Autowired是因为被@Inherited修饰过,所以子类才能继承父类的被注入字段。实际上@Inherited是这么用的:

@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface My {
}
@My // 用到类上才可以被子类SonService继承
@Service
public class FatherService {

    @Autowired
    public TargetService targetService;
}

Extension

如果我把上面的子类改为:

@Service
public class SonService extends FatherService{
    public TargetService targetService;
}

实际上这时,sonService有了两个字段:targetService父类的targetService。只不过父类的targetService属于隐形字段(在调用sonService.targetService调用的是targetService)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 注:都是在百度搜索整理的答案,如有侵权和错误,希告知更改。 一、哪些情况下的对象会被垃圾回收机制处理掉  当对象对...
    Jenchar阅读 3,253评论 3 2
  • 在经过一次没有准备的面试后,发现自己虽然写了两年的android代码,基础知识却忘的差不多了。这是程序员的大忌,没...
    猿来如痴阅读 2,898评论 3 10
  • #学童早餐日记# 烙饼➕小米粥➕韭菜炒鸡蛋 周五啦,好兴奋 早安[玫瑰][玫瑰]
    晨晨妈妈_8882阅读 275评论 0 0
  • 5/17小雅 采薇 采薇采薇,薇亦作止。曰归曰归,岁亦莫止。 靡室靡家,猃狁之故。不遑启居,猃狁之故。 采薇采薇,...
    铁卡阅读 341评论 0 0
  • 女儿的闺蜜小敏结婚还没有一年就离婚了, 那天,来到家里,没有了往日的活泼喜庆,拉了女儿进到屋里,关了房门,神神秘秘...
    半亩方塘yx阅读 529评论 8 9