简体   繁体   English

如何覆盖子类中的@Autowired属性

[英]How can I override @Autowired property in sub class

I decide to override autowired field in sub class. 我决定覆盖子类中的自动装配字段。 How can I do this override? 我该如何进行覆盖? Something like this 像这样

class Superclass {
    @Autowired
    Test test;

    public Test getTest() {
        return test;
    }
}

class Subclass extends Superclass {
    @Autowired
    Test2 test2;

    public Subclass() {
        super().test=test2;
    }
}

If understand correctly you want to have the value test2 auto filled and the method test() to use this new value. 如果正确理解,则希望自动填充值test2,并使用方法test()使用此新值。

There is no way in java to override a class variable, at least using a protected field will allow you to modify it's value in the subclass. Java中没有办法覆盖类变量,至少使用受保护的字段将允许您修改其在子类中的值。 But in this case i think it's better to override the getTest() method to return test2 instead. 但是在这种情况下,我认为最好重写getTest()方法来返回test2。

thanks from @dok solution i override field by this way: 感谢@dok解决方案,我通过这种方式覆盖了字段:

class Superclass {
    private Test test;

    @Autowired
    public Test getTest(Test test) {
        return this.test = test;
    }
}

class Subclass extends Superclass {
    @Override
    @Autowired
    public Test getTest(Test2 test2) {
        return super.getTest(test2);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM