title: Atomically maintaining service layer transactions and database logging with Spring framework
body: <p>I have a web application implemented using Spring and Hibernate. A typical controller method in the application looks like the following:</p>
  
  <pre><code>@RequestMapping(method = RequestMethod.POST)
  public @ResponseBody
  Foo saveFoo(@RequestBody Foo foo, HttpServletRequest request) throws Exception {
      // authorize
      User user = getAuthorizationService().authorizeUserFromRequest(request);
      // service call
      return fooService.saveFoo(foo);
  }
  </code></pre>
  
  <p>And a typical service class looks like the following:</p>
  
  <pre><code>@Service
  @Transactional
  public class FooService implements IFooService {
  
      @Autowired
      private IFooDao fooDao;
  
      @Override
      public Foo saveFoo(Foo foo) {
          // ...
      }
  }
  </code></pre>
  
  <p>Now, I want to create a <code>Log</code> object and insert it to database every time a <code>Foo</code> object is saved. These are my requirements:</p>
  
  <ul>
  <li>The <code>Log</code> object should contain <code>userId</code> from the authorised <code>User</code> object. </li>
  <li>The <code>Log</code> object should contain some properties from the <code>HttpServletRequest</code> object.</li>
  <li>The save operation and log creation operation should be atomic. I.e. if a foo object is saved in the object we should have a corresponding log in the database indicating the user and other properties of the operation.</li>
  </ul>
  
  <p>Since transaction management is handled in the service layer, creating the log and saving it in the controller violates the atomicity requirement.</p>
  
  <p>I could pass the <code>Log</code> object to the <code>FooService</code> but that seems to be violation of separation of concerns principle since logging is a cross cutting concern.</p>
  
  <p>I could move the transactional annotation to the controller which is not suggested in many of the places I have read.</p>
  
  <p>I have also read about accomplishing the job using spring AOP and interceptors about which I have very little experience. But they were using information already present in the service class and I could not figure out how to pass the information from <code>HttpServletRequest</code> or authorised <code>User</code> to that interceptors. </p>
  
  <p>I appreciate any direction or sample code to fulfill the requirements in this scenario. </p>