Reputation: 19287
I tried to create a service
directly through a class without implementing a customized interface
. And it works ! So I wonder why do most of people spend time on creating an interface in order to create a service
?
Upvotes: 2
Views: 87
Reputation: 611
I can point 2 reasons:
It helps decoupling. (Of course it is still possible to create decoupled classes without an interface.)
You added spring in the question tag, so this reason is specific: in many cases Spring needs an interface to properly create a jdk proxy (this is needed when using AOP). It is possible to create proxies without an interface (spring will use CGLIG instead of JDK), but there are some differences "under the hood". Check here.
Upvotes: 4
Reputation: 3170
First of all we are using service layer in order to wrap some business logic to our application.
To make our service layer more abstract from the client we will first create service Interface that will contains some of the abstract methods similar to CURD repository.
Then we need to write logic for our abstract methods in service interface by creating new class like ServiceImplementation.
So the control flow will be Controller to ServiceImplementation.
class StudentController {
ServiceImplementation serviceImpl;
// Endpoints implementation.
GET;
POST;
PUT;
DELETE;
}
interface Service {
List<StudentInfo> getAllStudents();
StudentInfo addStudent(Student std);
StudentInfo updateStudent(Student student);
StudentInfo findStudentById(String id);
boolean deleteStudent(String id);
}
public class ServiceImplementation implements Service{
private StudentRepository studentRepository;
// Implement the abstract methods
}
public interface StudentRepository extends JpaRepository<Student, String>{
}
This is the standard pattern we will follow.
Upvotes: -1