use @autowired in abstract base class

后端 未结 5 1597
失恋的感觉
失恋的感觉 2021-02-05 13:12

As I know, field injection is not recommended. Should use constructor instead.

What I\'m trying to do here is using @Autowired in

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-05 14:00

    You can't do it like this with constructor injection, you will have to extend the subclass constructor with the dependencies of the Base class constructor, and call the correct super constructor (standard Java rules still apply, even if you use Spring).

    Field and Setter injection will do this correctly however.

    I would recommend Field injection in any case, as it reduces code duplication. Compare:

    class A {
        @Autowired private Field field;
    }
    

    Vs.

    class A {
        private final Field field;
    
        /** plus mandatory javadocs */
        @Autowired
        public A(Field field) {
            this.field = field;
        }
    }
    

    In the constructor injection example you repeat yourself four times just to get a field set the way you want it... even though I love having things final, this kind of duplication just makes it hard to change code.

提交回复
热议问题