title: Allow method execution only if the caller is of certain type
body: <p>We have an <code>XRepository</code> which extends <code>JpaRepository</code>. Since deleting <code>X</code> entities got pretty ad-hoc recently we created an <code>XDeletionService</code> which contains lots of... stuff :-) and uses the <code>XRepository</code>.</p>
  <p>Now we have an interesting idea to forbid the execution of any <code>delete</code> methods in the <code>XRepository</code> unless these are called from within the <code>XDeletionService</code>. E.g. if a colleague calls directly by mistake <code>XRepository.delete(..)</code> from within <code>TheirService</code> it will throw an exception.</p>
  <p>We still cannot find an elegant solution for this idea. What we did so far is to create an aspect with a pointcut expression which matches the delete methods of the repository. This aspect throws an exception by consulting the stacktrace, e.g.:</p>
  <pre><code>boolean calledFromXDeletionService = Arrays.stream(Thread.currentThread().getStackTrace())
          .anyMatch(stackTraceElement -&gt;
              XDeletionService.class.getName().equals(stackTraceElement.getClassName())); 
  if (!calledFromXDeletionService)
     throw new ....
  </code></pre>
  <p>This seems pretty ugly though. Do you have a better idea how to implement this &quot;feature&quot;?</p>