Home > other >  Springboot: Compilation error while autowiring the parent class
Springboot: Compilation error while autowiring the parent class

Time:05-20

All,
I am trying to autowire a parent class which has a child class with additional methods. As far as I know, Spring will inject an instance of a child class to a parent class reference. To be sure, I even added a qualifier, but I am getting a compilation error. Please advice on how to resolve this.

Here is the code

Parent class:

@Service
Class Student {

    void doSomething (int i) {
    }
}

Child class:

@Service
@Qualifier("childclass")
Class ScholarStudent extends Student {
    void doAnotherThing (int i) {
    }
}

Controller:


@RestController
Class StudentController {
    @Autowired
    @Qualifier("childclass")
    Student student;

    @GetMapping(value = "/students/{studentId}")
    public restCallFromFE (@PathVariable int studentId) {
         student.doAnotherThing (studentId);
    }
}

I get a compilation error here stating
The method doAnotherThing() is undefined for the type Student.

(Will try to attach an image here) I can understand this is because the method is not defined in the parent class. But how do I resolve this with autowiring? Thanks in advance to everyone who responds.

CodePudding user response:

You cannot call the method of a child class from the reference to a base class that's not declared in the base class in any way.

To fix this you'll have to make your Student an interface or an abstract class that declares all the methods the child classes will have (and maybe implements some of them itself). If you don't need all of those methods in a single Student interface, just split it into multiple interfaces and autowire those which have the methods required for the concrete usage.

CodePudding user response:

Try this:

@RestController
Class StudentController {
    @Autowired
    @Qualifier("childclass")
    Student student;

    @GetMapping(value = "/students/{studentId}")
    public restCallFromFE(@PathVariable int studentId) {
         if (student instanceof ScholarStudent) {
             var scholar = (ScholarStudent)student;
             scholar.doAnotherThing(studentId);
         }
    }
}

Note that you may want to consider looking at polymorphic methods (eg: overloading doSomething(int i) instead of creating a separate method) if you don't want consumers to know the specialised class type.

  • Related