Ş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ı
- Service Facade design patternini uygulamak.
- Bazı özel business logicler için orta katman oluşturmak.
- 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.
public interface StudentRepository {
void save(Student student);
}@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.
public interface StudentService {
void save(Student student);
}@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ı
@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();
}
}