0

I want to create a custom annotation (method scoped) that will insert in database. This annotation will be attached to every method in my rest controller so that when an api call is made, the annotation saves the action made in a track-user table in database

so far i created the annotation interface, i think i need to add a method that saves the action&author in the track-user table but i don't know where or how:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionLog {
    String action() default "UNDEFINED";
    String author() default "UNDEFINED";
}

I want to use it like that:

@ActionLog(author="John",action="get all users")
public List<User> getAllUsers() { return repo.findAll(); }

Then in my database i should have a new insert of the action with its author

Amine Ben
  • 1
  • 4
  • That depends on what framework you're using. Does it support interceptors or some other form of AOP? – ernest_k Feb 06 '19 at 11:00
  • actualy i was asked not to use AOP – Amine Ben Feb 06 '19 at 11:01
  • What are you currently using for your rest services? (the tags don't make it obvious) – ernest_k Feb 06 '19 at 11:04
  • just updated the tags, it's a simple rest-spring-boot app – Amine Ben Feb 06 '19 at 11:08
  • This would be a shoe in for AOP. Why are you not allowed to use it? – Torben Feb 06 '19 at 11:10
  • actualy the app is pretty big and has some restrictions in AOP and i'm not allowed to play with it cauze i might change something that i shouldn't touch, that was my manager's answer... – Amine Ben Feb 06 '19 at 11:13
  • An annotation doesn't do anything. It is metadata, nothing more nothing less. You either need an annotation processor to generate additional code that does the inserts or use AOP to do the same. – M. Deinum Feb 06 '19 at 11:18
  • but still @Torben , what would be your solution if i can use AOP? – Amine Ben Feb 06 '19 at 11:18
  • Seems like a silly justification from your manager. Maybe they don't understand AOP properly? You would create an aspect and define that it is run specifically @Around a specified annotation. Only the methods marked with the annotation listed in the aspect would be affected. Just what you would want. – Torben Feb 06 '19 at 11:49

1 Answers1

0

To create your own annotation you have to first create an interface which you have done already than you have to write an Aspect class for the same.

@Component
@Aspect
public class ActionLogAspect {


  @Around(value = "@annotation(ActionLog)", argNames = "ActionLog")
  public  getUsersByAuthorName(ProceedingJoinPoint joinPoint, ActionLog actionLog) throws Throwable {

    List<User> userList = new ArrayList();

     //Your Logic for getting user from db using Hibernate or Jpa goes here.
     //You can call your functions here to fetch action and author by using
    // actionLog.action() and actionLog.author()

    return userList;
    }

}