Search code examples
springtransactionsaopcross-cutting-concerns

Why to use AOP for transaction management in Spring?


I am learning AOP and came to know that is useful for separation of concern, for example, logging, transaction management, security etc.

So far good to know AOP.

Now, I read about Spring transaction management in Spring framework we can have annotation @Transactional.

It is this point which is make me confused why should we use AOP in which we have to create Aspects rather than using the annotation which Spring provides.

For example:

@Transactional
public void dataAccessTrans() {

}

When Spring is already having transaction related functionality, then why should we use AOP to do transaction management?

If we use AOP, then don't we have to create Aspect and create advice which would act on the method; does't this make us to do manual work, rather than handling it by spring framework itself by its own annotations.

Can anyone help me understand this which I am not able to understand clearly.


Solution

  • Spring relies on AOP to implement declarative transactions.

    The Spring Framework’s declarative transaction management is made possible with Spring aspect-oriented programming (AOP), although, as the transactional aspects code comes with the Spring Framework distribution and may be used in a boilerplate fashion, AOP concepts do not generally have to be understood to make effective use of this code.

    So as you use the @Transactional annotation :

    @Transactional
    public void dataAccessTrans() {
      ...
    }
    

    you use indirectly AOP.
    So in the very most of cases, you never need to declare any custom aspects to handle the transaction management.