Home > front end >  How to implement Spring Boot service classes without using impl and using a interface as dependency
How to implement Spring Boot service classes without using impl and using a interface as dependency

Time:11-28

I am trying to implement a Spring Boot REST API but I was asked to use a interface as dependency but no impl, and I don't know how to achieve this. The way I implemented was to have service classes for my entities and there I would just call the repository in my methods. I would like an example of implementation like this.

I watched some youtube tutorials but they all used impl classes

CodePudding user response:

Your controller should have a field of your interface type, with the injecting annotation (in spring it's @Autowired). The DI framework will do the heavy-lifting on startup and inject the correct implementation at runtime

@Controller
public class MyController {
    @Autowired    
    private MyInterface myInterface;
    ....
}

For this to work, your framework needs to recognize the concrete class. In spring you can achieve this in multiple ways - scanning package paths, xml configuration files and more.

Check the spring documentation to see which way suits you best

  • Related