annotations in spring-boot

0

Reviewing a bit about the concepts of spring-boot, I saw that there is @Component which is divided into 3

@Controller
@Service
@Repository

Reading a little, each one has an end, come to the conclusion that

@Controller -->sirve para las presentaciones
@Service    -->sirve para los servicios
@Repository -->sirve para las persistencias

I am not very clear about the presentations, what is a presentation? A controller is not the one in charge of linking the view with the logic of the business?

    
asked by x-rw 26.04.2017 в 16:45
source

2 answers

2

Hello good day, I'll tell you a little about stereotypes de Spring:

What are the Spring Stereotypes? . Spring defines a set of core annotations that categorize each of the components associating a specific responsibility.

If we see it as a diagram we have at the top level:

                 **@Component**



**@Repository**    **@Controller**    **@Service**

@Component : It is the general stereotype and allows you to write down a bean so that Spring considers it one of its objects.

@Repository : It is the stereotype that is responsible for registering a bean to implement the repository pattern that is responsible for storing data in a database or repository of information that is needed . By marking the bean with this annotation Spring provides cross-sectional services such as conversion of exception types.

**@Repository** ----------------> BD

@Service : This stereotype is responsible for managing the most important business operations at the application level and agglutinates calls to several repositories simultaneously. Its fundamental task is that of aggregator.

                   |----@Repository
                   |----@Repository
@Service  ---------|----@Repository
                   |----@Repository
                   |----@Repository

@Controller : The last of the stereotypes that is the one that performs the tasks of controller and management of the communication between the user and the application. For this, it is usually supported by a template engine or a library of labels that facilitate the creation of pages.

@Controller  ------------>   @Service --------------> @Repository
    |                                       |
    |                                       |--------> @Repository
    |                                       |
    |                                       |--------> @Repository
    |                                       |   
   VIEW                                     |--------> @Repository

I add example:

@Repository
public class CircleDaoImpl implements CircleDao
{
    private Point center;
    ----
}

@Service
public class CircleServiceImpl implements CircleService
{
    private Point center;
    ----
}

@Controller
public class CircleController
{
    private Point center;
    ----
}
    
answered by 26.04.2017 / 17:11
source
1

These annotations are based on the MVC pattern. Namely:

Classes decorated with the @Controller annotation serve as the MVC C. It should be noted that the real controller in Spring MVC is the class DispatchServlet that will use the specific @Controller classes to attend the requests based on the mapping of the declared URLs.

Classes decorated with the @Service notation should serve for your service layer or business logic. This is where you put the business logic of your application, business rules, among others .

Classes decorated with the annotation @Repository should serve for the data access layer. Here you should place the CRUD logic: insert, update (update), deletion (physical and / or logical), queries (select).

The @Service , @Repository and your entity classes will be the MVC M. Your JSP files and other view technologies (JSTL, mustache, etc) make up the MVC V.

The @Controller classes should only access the @Service classes through interfaces. Similarly, the @Service classes should only access other classes @Service and a specific set of classes @Repository through interfaces.

Example:

//Entidades
public class Recibo {
    private List<DetalleRecibo>
}
public class Producto { }
public class DetalleRecibo {
    Producto producto;
}

//DAOs, Repositorios, etc
public interface ReciboDao {
    void guardar(Recibo recibo);
}
//nota: estas anotaciones van a nivel de clase, NO a nivel de interfaz
@Repository
public class ReciboDaoImpl implements ReciboDao {
    //implementa los métodos
    //puede mandarlo a archivo, usar JDBC u otro framework
    //como Hibernate, JPA, MyBatis, jOOQ
    //o usar un repositorio de datos externo como servicios REST
}

public interface ProductoDao {
    Producto obtener(int id);
    void actualizar(Producto producto);
}
@Repository
public class ProductoDaoImpl implements ProductoDao {
    //implementación...
}

//Service
public interface ProductoService {
    Producto obtener(int id);
    void actualizarStock(Producto productoConStockActualizado);
}
@Service
public class ProductoServiceImpl implements ProductoService {
    //se le asocia al ProductoDao (interfaz)
    //ojo que debería acceder de manera vertical/jerárquica
    //al dao asociado a la entidad Producto
    @Autowired
    private ProductoDao productoDao;

    @Override
    public Producto obtener(int id) {
        return productoDao.obtener(id);
    }

    @Override
    public void actualizarStock(Producto productoConStockActualizado) {
        //ejemplo minimalista y básico
        //la implementación de un caso de uso como el de aquí debería
        //considerar más elementos
        Producto actual = obtener(productoConStockActualizado.getId());
        if (actual.getStock() - productoConStockActualizado.getStock() < 0)
            throw new MiExcepcion("Producto no puede tener stock negativo");
        productoDao.actualizar(productoConStockActualizado);
    }
}

public interface ReciboService {
    Recibo generaRecibo(List<DetalleRecibo> listaDetalleRecibo);
    void guardar(Recibo recibo);
}
@Service
public class ReciboServiceImpl {
    //se le asocia a ReciboDao, similar a la relación
    //entre ProductoService y ProductoDao
    @Autowired
    private ReciboDao reciboDao;
    //Nota: si ReciboServiceImpl quiere consultar u operar
    //con la información de la entidad Producto
    //en lugar de asociarse a ProductoDao se asociará
    //a ProductoService puesto que su implementación posee
    //reglas de negocio a usar en la aplicación
    @Autowired
    private ProductoService productoService;

    @Override
    public Recibo generaRecibo(List<DetalleRecibo> listaDetalleRecibo) {
        //usar la información de detalle del recibo
        //para armar y generar un recibo
        //ejemplo
        for (DetalleRecibo detalle : listaDetalleRecibo) {
            Producto producto = detalle.getProducto();
            productoService.actualizarStock(producto);
        }
        //más procesamiento...
        //se retorna el recibo generado
    }

    @Override
    public void guardar(Recibo recibo) {
        reciboDao.guardar(recibo);
    }
}

@Controller
public class VentaController {
    @Autowired
    private ReciboService reciboService;

    @RequestMapping(...)
    public void guardaRecibo() {
        //procesa la información recibida
        //genera el recibo, lo guarda, etc...
    }
}

Adapted from my response on the English site .

    
answered by 26.04.2017 в 17:15