Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

333
Visualizações
What belongs to the Controller-layer, what to the Service-layer?

I have a simple Spring-Boot Restful Application. I have a Controller-layer and a Repository-layer, but no Service-layer. Let me show you one of my Controller methods:

@RequestMapping(value = "users/{id}", method = RequestMethod.GET)
public Resource<UserResource> get(@PathVariable Long id) throws NotFoundException {
    log.info("Invoked method: get with ID: " + id);
    log.warn("Searching for user with ID " + id);
    User user = userRepository.findOne(id);
    if (user == null){
        log.error("Unexpected error, User with ID " + id + " not found");
        throw new NotFoundException("User with ID " + id + " not found");
    }
    log.info("User found. Sending request back. ID of user is " + id);
    return new Resource<UserResource>(getUserResource(user));
}

Since I have no Service-layer, my Controller does the Business logic for me. Now I want to implement the Service-layer. What should / shouldn't my Controller do?

Should my Service-layer (which I want to implement now) do all the work and my Controller only delegates the request to the Service-layer?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Ask yourself: what needs to change if I want to render results for a different view/transport/protocol? That belongs in the controller.

Code in the Controller layer should only be related to mapping business input/output between the Service layer to the view/transport/protocol (as appropriate). This might (or might not) include mapping business data into JSON (it's not unreasonable for your business/service layer to work directly with JSON or similar), XML, HTML, or whatever your content type might be (for HTTP).

While your Controller may feel lightweight, keep in mind that Spring's backing of the controller does much of the work - think of such a "simple" controller as a anchor-point that your framework recognizes and hangs all the heavier, boiler-plate, code off of, to your benefit.

over 4 years ago · Santiago Trujillo Relatório

0

Service Class

public class UserService {
     public User findUser(String id){
          log.info("Invoked method: get with ID: " + id);
          log.warn("Searching for user with ID " + id);
          User user = userRepository.findOne(id);
          if (user == null){
            log.error("Unexpected error, User with ID " + id + " not found");
            throw new NotFoundException("User with ID " + id + " not found");
          }
         log.info("User found. Sending request back. ID of user is " + id);
         return user;
     }
}

API class

    @RequestMapping(value = "users/{id}", method = RequestMethod.GET)
    public Resource<UserResource> get(@PathVariable Long id) throws    NotFoundException {
          return new Resource<UserResource>(userService.findUser(id));
    }

Add common exception handler NotFoundException to redirect to proper error page.

over 4 years ago · Santiago Trujillo Relatório

0

 public class UserService{

     public User findUser(String id){
          log.info("Invoked method: get with ID: " + id);
          log.warn("Searching for user with ID " + id);
          User user = userRepository.findOne(id); 
          log.info("User found. Sending request back. ID of user is " + id);
          return user;
      }
    }




@RequestMapping(value = "users/{id}", method = RequestMethod.GET)
public Resource<UserResource> get(@PathVariable Long id) throws NotFoundException {
      User user = userService.findUser(id)
      if (user == null){
           log.error("Unexpected error, User with ID " + id + " not found");
           throw new NotFoundException("User with ID " + id + " not found");
      }
      return new Resource<UserResource>(getUserResource(user));
 }
}

Based in @Jai response the only difference is the if, because sometimes you need to receive a user null

public void anotherMethod(@PathVariable Long id){
    User user = userService.findOne(id);
    if(user == null) {
        //in this case I don't want to throw NotFoundException and make some other logic like create the user for example.
    }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda