use @autowired in abstract base class

后端 未结 5 1585
失恋的感觉
失恋的感觉 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:04

    The code that you provide won't compile. As long as in your base class you don't have the default constructor, you should call super(MyDemoService) in child.

    Inherited(sub) class:

    public class Sub extends Base {
    
        private final MySubService mySubService;
    
        @Autowired
        public Sub(MySubService mySubService, MyDemoService myDemoService){
            super(myDemoService);
            this.mySubService = mySubService;
        }
    } 
    

    Or, if MySubService is an implementation of MyDemoService

    @Autowired
    public Sub(MySubService mySubService){
        super(mySubService);
    }
    

    As long as your field MyDemoService myDemoService in abstract class is protected you can use it in subclasses.

    If you have multiple implementation of MyDemoService, than you have to use @Qualifier as described in the answer that you have mentioned.

    public Sub(@Qualifier("MySubService") MyDemoService mySubService){
        super(mySubService);
    }
    

提交回复
热议问题