Post

Spring Abstract Controller

Spring Abstract Controller

Crear un controllador generico por defecto para servicios rest:

  • Prerequisitos
  • Crear Controllador Genérico.
  • Crear Servicio Genérico.
  • Crear Componentes T, K, I, M

Prerequisitos

  • Configurar un proyecto spring boot multimodulo

Crear Controller Genérico.

El controller, el service y el resto de componentes se crean en la librería commons-lib. Esto permite que el resto de módulos lo puedan utilzar.

Controlador con las funciones CRUD y un buscador generico con un filtro (opcional) T: Dto. para creación. K: Dto. respuesta. I: Dto. filtro. M: Dto. modificación.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@RestController
public abstract class AbstractRestController<T, K, I, M> {

    protected final CrudService<T, K, I, M> service;

    public AbstractRestController(CrudService<T, K, I, M> service) {
        this.service = service;
    }

    @GetMapping
    public ResponseEntity<List<K>> getAll(I filter) {
        return ResponseEntity.ok(service.findAll(filter));
    }

    @GetMapping("/{id}")
    public ResponseEntity<K> getById(@PathVariable Long id) {
        return service.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<K> create(@RequestBody T entity) {
        K createdEntity = service.save(entity);
        return new ResponseEntity<>(createdEntity, HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<K> update(@PathVariable Long id, @RequestBody M entity) {
        K updatedEntity = service.update(id, entity);
        return ResponseEntity.ok(updatedEntity);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        service.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}

Este controlador se configura con un servicio genérico: CrudService<T, K, I, M> service

Crear Servicio Genérico.

Un servicio genérico que los servicios sobreescriben.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public interface CrudService<T, K, I, M> {
	default List<K> findAll(I filter) {
		throw new UnsupportedOperationException(ConstantUtil.NOT_IMPLEMENTED_EXCEPTION);
	};

	default Optional<K> findById(Long id) {
		throw new UnsupportedOperationException(ConstantUtil.NOT_IMPLEMENTED_EXCEPTION);
	};

	default K save(T entity) {
		throw new UnsupportedOperationException(ConstantUtil.NOT_IMPLEMENTED_EXCEPTION);
	};

	default K update(Long id, M entity) {
		throw new UnsupportedOperationException(ConstantUtil.NOT_IMPLEMENTED_EXCEPTION);
	};

	default void deleteById(Long id) {
		throw new UnsupportedOperationException(ConstantUtil.NOT_IMPLEMENTED_EXCEPTION);
	};
}

Crear Componentes T, K, I, M

El resto de componentes son Dto. que también se definen en common-lib. Se organizan en paquetes para cada módulo. Ejm.: com.example.spring.modulith.dto.customer

T: CustomerRequest T: CustomerResponse T: CustomerFilter T: CustomerUpdate

This post is licensed under CC BY 4.0 by the author.