title: How to create transaction in Spring Boot aop @Around function?
body: <p>I want to implement an authorization method by using Spring Boot AOP. The original idea is, if the return object return from the REST calls didn't pass the authorization check, it will throw a unauthorized exception.</p>
  
  <p>I'm doing it like this:</p>
  
  <pre class="lang-java prettyprint-override"><code>@Aspect
  @Component
  public class AuthAspect {
    @Around("AllRestExecPoint()")
    public Object auth(ProceedingJoinPoint point) throws Throwable {
      Object returnObject = point.proceed();
      if (!checkAuthorization(returnObject)) {
        throw new UnauthException();
      }
      return returnObject;
    }
  }
  </code></pre>
  
  <p>However, the problem is, if this REST service will execute some INSERT or UPDATE to my DB, it will commit before my authorization checks. Therefore, the <code>UnauthException</code> will be thrown but the transaction is still committed.</p>
  
  <p>The first try I want to manually create transaction before the <code>proceed()</code> call and commit it before return, but it failed.</p>
  
  <pre class="lang-java prettyprint-override"><code>@Aspect
  @Component
  public class AuthAspect {
    private final EntityManager em;
  
    @Autowired
    public AuthAspect(EntityManager em) {
      this.em = em;
    }
  
    @Around("AllRestExecPoint()")
    public Object auth(ProceedingJoinPoint point) throws Throwable {
      em.getTransaction().begin();
  
      Object returnObject = point.proceed();
      if (!checkAuthorization(returnObject)) {
        throw new UnauthException();
      }
  
      em.getTransaction().commit();
  
      return returnObject;
    }
  }
  </code></pre>
  
  <p>It will cause the <code>java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead</code>.</p>
  
  <p>I searched on the internet and some answers need to modify <code>web.xml</code> file, but I don't want to use xml to do the configuration.</p>