javaspringspring-bootmodel-view-controllerdependency-injection

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();
    }
}

Solution

  • Please understand basic Java and use of interface . Spring boot is just abstraction over Java hence all the basic concepts applies as it is.

    Coming back to your questions IBoxService is a interface which allows to inject required implementation of it at controller level. As of now only implementation of IBoxServic is BoxService hence it is getting injected automatically. In case you have multiple implementations you need to use qualifier annotation to specify kind of implementation you need to inject. Or you can create object bu yourself using class names

    Consider below:

    IBoxService is implemented by two classes BoxService and TiffinBoxService

    Now in controller you can inject implementation which you want. Which allow us to achieve principle of interface which is hide internal details.

    User which is controller in this case doesn't need to know which class is being use internally as we are using reference of interface.

    List interface is best example which has ArrayList and LinkedList as implementation classes.

    Hope it is useful !!