Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of Service Interface Class in Spring Boot

My question is regarding the use of the interface class. I am fairly new to Spring so please bear with me if this is overly simple.

First of all, what is the point of having an IBoxService interface here when you could just declare the find all in BoxService. Secondly, in the controller how is IBoxService being used. Meaning, we are calling IBoxService.findAll(). But, how is this being tied to the BoxService class. What if multiple service classes implemented IBoxService? Is this a java thing or a Spring injection thing. Thanks.

package com.xyz.service;

import com.xyz.model.Box;
import java.util.Set;

public interface IBoxService {

    Set<Box> findAll();
}

package com.xyz.service;

import com.xyz.model.Box;
import com.xyz.repository.BoxRepository;
import java.util.Set;
import org.springframework.stereotype.Service;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;

@Service
@AllArgsConstructor
@Slf4j
@Transactional
public class BoxService implements IBoxService {
@Autowired
private BoxRepository boxRepo;

@Override
public Set<City> findAll() {

    return (Set<City>) repository.findAll();
}

}

package com.xyz.controller;

import com.xyz.model.Box;
import com.xyz.service.IBoxService;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;    

@RestController
@RequestMapping("/api/box")
public class BoxController {

    @Autowired
    private IBoxService boxService;

    @GetMapping
    public ResponseEntity<Set<Boxes>> allBoxes() {

        return (Set<Box>) boxService.findAll();
    }
}
like image 878
please_help_im_confused Avatar asked Dec 13 '22 08:12

please_help_im_confused


1 Answers

There are various reasons why Service layer interfaces are created. The first and most important reason is testability. You can create mocks of service interface and test your code easily, if you cannot create mocks using a mocking library then you can create test stubs.

One more reason is, we can achieve loose coupling between Controller and Service layer. Suppose you want to entirely change the implementation of service, you can create new service implementation and inject that implementation by injecting new bean by qualifier name

like image 132
Govinda Sakhare Avatar answered Jan 04 '23 20:01

Govinda Sakhare