Spring can you autowire inside an abstract class?

后端 未结 4 2007
长情又很酷
长情又很酷 2020-11-30 02:14

Spring is failing to autowire my object? Is it possible to autowire an object within an abstract class. Assume all schemas are supplied in application-context.xml

Qu

4条回答
  •  余生分开走
    2020-11-30 02:44

    What if you need any database operation in SuperGirl you would inject it again into SuperGirl.

    I think the main idea is using the same object reference in different classes. So what about this:

    //There is no annotation about Spring in the abstract part.
    abstract class SuperMan {
    
    
        private final DatabaseService databaseService;
    
        public SuperMan(DatabaseService databaseService) {
         this.databaseService = databaseService;
        }
    
        abstract void Fly();
    
        protected void doSuperPowerAction(Thing thing) {
    
            //busy code
    
            databaseService.save(thing);
    
        }
    }
    

    @Component
    public class SuperGirl extends SuperMan {
    
    private final DatabaseService databaseService;
    
    @Autowired
    public SuperGirl (DatabaseService databaseService) {
         super(databaseService);
         this.databaseService = databaseService;
        }
    
    @Override
    public void Fly() {
        //busy code
    }
    
    public doSomethingSuperGirlDoes() {
    
        //busy code
    
        doSuperPowerAction(thing)
    
    }
    

    In my opinion, inject once run everywhere :)

提交回复
热议问题