-2

i am new to spring

in my spring web project DAO and service they created the interface and implementing it created class. can we liminate interface.

  • 2
    why you want to eliminate interface? – lakshman Jan 29 '20 at 09:14
  • 2
    Interface gives you flexibility, in case in future you want to pass it with some different implementaion. – Gaurav Gupta Jan 29 '20 at 09:15
  • @Sangam.R, It's a design pattern. Please check about the design pattern https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm – Srini Jan 29 '20 at 09:21
  • 1
    https://stackoverflow.com/questions/256255/spring-and-interfaces – R.G Jan 29 '20 at 09:26
  • A better explanation to it can be found [here](https://stackoverflow.com/questions/256255/spring-and-interfaces). – Himanshu Jain Jan 29 '20 at 10:24
  • It seems that you need to go through Java Core and design patterns first because it seems you still cannot understand why interfaces are required overall in Java. – zawarudo Jan 29 '20 at 12:35

1 Answers1

0

The whole point of using interface is to create abstraction. When you call you DAO from Service, your service is not aware of the actual implementation of DAO/ cases in which you have multiple implementations of your DAO interface, your service is not aware of the actual impl being used.

With spring you will use - Autowire to inject the dependency. You will refer your Dependency using interface.

    @Component/@Service
    class ServiceImpl {
      @Autowired
      private DAOInterface dao;

      // Rest of code
    }

Spring knows - to create the instance of this ServiceImpl it needs to inject a concrete impl of DAOInterface type. In case you have concrete implementation, it does so. In case you have multiple impls - you need to define by bean name which implementation you need using @Qualifier.

Interface is kind of a contract for your impl classes. Other than abstracting the actual impl, it helps you decoupling the layers by not directly having a dependency on the concrete classes. This is a good design pattern

Priyak Dey
  • 1,227
  • 8
  • 20