use @autowired in abstract base class

后端 未结 5 1599
失恋的感觉
失恋的感觉 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 13:45

    I'd suggest using @Configuration classes. That way you can remove Spring annotations entirely from your business classes:

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

    Spring config:

    @Configuration
    public class SubConfig{
    
        @Bean
        public Sub sub(MySubService subService, MyDemoService demoService){
            return new Sub(subService, demoService);
        }
    }
    

    With Configuration classes, you no longer rely on magical classpath scanning, but actually instantiate beans manually again. There's a lot less surprises in this approach.

提交回复
热议问题