Tengo una aplicación Restful Spring-Boot simple. Tengo una capa de controlador y una capa de repositorio, pero no tengo una capa de servicio. Déjame mostrarte uno de mis métodos de controlador:
@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)); }Como no tengo una capa de servicio, mi controlador hace la lógica comercial por mí. Ahora quiero implementar la capa de servicio. ¿Qué debe/no debe hacer mi controlador?
¿Debería mi capa de servicio (que quiero implementar ahora) hacer todo el trabajo y mi controlador solo delega la solicitud a la capa de servicio?
Pregúntese: ¿qué debe cambiar si quiero generar resultados para una vista/transporte/protocolo diferente? Eso pertenece al controlador.
El código en la capa del controlador solo debe estar relacionado con la asignación de entrada/salida comercial entre la capa de servicio y la vista/transporte/protocolo (según corresponda). Esto podría (o no) incluir el mapeo de datos comerciales en JSON (no es descabellado que su capa de negocios/servicios funcione directamente con JSON o similar), XML, HTML o cualquiera que sea su tipo de contenido (para HTTP).
Si bien su controlador puede parecer liviano, tenga en cuenta que el respaldo de Spring del controlador hace gran parte del trabajo: piense en un controlador tan "simple" como un punto de anclaje que su marco reconoce y cuelga todo el código más pesado, repetitivo. fuera de, para su beneficio.
Clase de servicio
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; } }clase de API
@RequestMapping(value = "users/{id}", method = RequestMethod.GET) public Resource<UserResource> get(@PathVariable Long id) throws NotFoundException { return new Resource<UserResource>(userService.findUser(id)); }Agregue el controlador de excepciones común NotFoundException para redirigir a la página de error adecuada.
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)); } }Basado en la respuesta de @Jai, la única diferencia es el si, porque a veces necesita recibir un usuario nulo
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. } }