How to implement Service Layer with Spring?

Asked

Viewed 226 times

3

Does anyone know any tutorial, examples... any source to learn how to implement service layer?

1 answer

3


The service layer is where you will have all your business rules before persistence and of course where you will control the database transaction.

//declare aqui a anotação service
@Service
public class MyService {

      ...
}

For transaction control use @Transactional(readonly = true) by default spring already sets up the transaction for only the commit when everything goes right in your method.

You can change this with :

 @Transactional(propagation=Propagation.REQUIRED,readOnly=false) 
    public void save(ProductTech product) { 
        currentSession().save(product); 
        System.out.println(“product saved with sucess”); 
    } 

PROPAGATION_MANDATORY: Requires the use of a transaction, if there is no current transaction, an exception is made.

PROPAGATION_NESTED: Executes within a nested transaction if a current transaction exists.

PROPAGATION_NEVER: Prevents the use of a transaction. If there is a current transaction, an exception is made.

PROPAGATION_NOT_SUPPORTED: Does not use the current transaction. It is always executed without any transaction.

PROPAGATION_REQUIRED: Uses the current transaction if it exists, if it does not exist creates a new transaction.

PROPAGATION_REQUIRES_NEW: Create a new transaction, if a current already exists, suspend it.

PROPAGATION_SUPPORTS: Uses the current transaction if it exists, otherwise executes without transaction.

Ready after that just inject your Service into your Controller

  • I saw that it is possible to maintain Dao with the operations in the bank and the service for the business logic. To use my service class I just note with @service and inject it into the controller and call the methods I created? Do you have any convention in the name of methods? How many service classes do you need to maintain cohesion?

  • @Matheussilva If you need more details, edit your question or ask more specific questions. Comments are not suitable for adding content. Also consider that your new questions can be very broad or based on opinions, because there are many conventions and the number of classes is something that depends a lot on the system in question. I suggest you read about [Ask]. Abraco!

  • @Matheussilva if you took your question mark as answered please

Browser other questions tagged

You are not signed in. Login or sign up in order to post.