Şimdi bizim REST Controllerımızda birden fazla DAO katmanı ile entegrasyon sürecimizde artık 5 tane DAO katmanımızda repository olduğunda artık REST Controllerımızda her defasında 5'er tane Repository katmanlarını inject ediyor olacağız, bunun alternatif çözümü olarak araya bir servis (service) katmanı eklemektir.

Service Katmanının amacı

  1. Service Facade design patternini uygulamak.
  2. Bazı özel business logicler için orta katman oluşturmak.
  3. Birden fazla gelen veri kaynaklarını birleştirmek.

Service katmanını tanımlamak için @Service annotationunu kullanırız.

@Service annotationunu Service implementationlarına ekleriz ve Spring otomatik olarak bu Servisi component-scanning sayesinde injection için kayıt edecektir.

Şimdi bizim Student.java classımıza DAO ve Service katmanlarını ekleyelim.

Öncelikle



1.Repo Katmanı

data.repository package altındaki repo katmanlarımızı yazalım.

StudentRepository.java

public interface StudentRepository {
    void save(Student student);
}

StudentRepositoryImpl.java

@Repository
public class StudentRepositoryImpl implements StudentRepository {
    private EntityManager entityManager;
    @Autowired
    public StudentRepositoryImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
    @Override
    public void save(Student student) {
        this.entityManager.persist(student);
    }
}


2.Service Katmanı

Şimdi de service katmanımızı yazalım.

StudentService.java

public interface StudentService {
    void save(Student student);
}

StudentServiceImpl.java

@Service
public class StudentServiceImpl implements StudentService {
 
    private StudentRepository studentRepo;
 
    @Autowired
    public StudentServiceImpl(StudentRepository studentRepo) {
        this.studentRepo = studentRepo;
    }
 
    @Override
    @Transactional
    public void save(Student student) {
        this.studentRepo.save(student);
        System.out.println("Öğrenci kaydedildi.");
    }
 
}


Not: Artık bizim yazdığımız @Transactional annotationun yeri Repo katmanında değil Service katmanındadır.

3.Controller Katmanı

StudentRestController.java

@RestController
public class StudentRestController {
        
    private StudentService studentService;
 
    @Autowired
    public StudentRestController(StudentService studentService) {
        this.studentService = studentService;
    }
    
    @RequestMapping(path="/students",method=RequestMethod.POST)
    public ResponseEntity<?> saveStudent(@RequestBody Student student){
        this.studentService.save(student);
        return ResponseEntity
                .status(HttpStatus.OK)
                .build();
    }
}