1

What I want to do is to create a custom annotation to use it on a Service, and each time a method is called from there first execute something. For example:

@CustomAnnotation
public Class MyService{

   public void myMethod(){
      //do something
   }
}

And when myMethod is called, do something before its code is executed, and then do what it has to do. Is there any way to do that? I need to do it with annotations, using interfaces or inheritance for that is useless because is for each method, not just one.

I know how to scan a package to get the classes annotated, but I don't know how to check it at runtime when the app is running.

Thank you!

Motomine
  • 4,205
  • 5
  • 20
  • 23
  • http://www.oracle.com/technetwork/articles/hunter-meta-3-092019.html – PM 77-1 Apr 05 '17 at 19:39
  • Thank you for the answers! The methods annotated with Around and Aspect are automatically executed? If I define the behavior there it should work well after running mvn install? – Motomine Apr 05 '17 at 20:07
  • According to your original post it is more like "before advice", not "around", but you'll figure it out. Well... they *should* be automatically executed, *but* preparations must be made. I don't speak English well enough to explain briefly and clearly, but you should investigate "weaving". To make advices run, weaving must be made (either based on reflection or code-generation) and it somehow interferes compilation process, some specific compiler must be used or something like that. When I used aop, I had all spring infrastructure set up for me, so I don't know the details. But it must work – Mikhail Antonov Apr 05 '17 at 20:58
  • Thank you for your help! I followed a tutorial and it's not working, could you please help me? The question is [here](http://stackoverflow.com/questions/43260618/aspectj-does-not-execute-the-pointcut) – Motomine Apr 06 '17 at 17:13

1 Answers1

0

It seems that what you need may be achieved by using AOP (aspect oriented programming).

Ive posted the code example here. It executes some code before the annotated methods and doesn't execute for others.

AOP allows you to do that without intervention in code of method-containing classes, you may alter methods behavior without altering methods themselves and their invocation code. You may even skip method execution using this technique (using @Around advice). It is useful if you need security checks before allowing method execution, for example.

Community
  • 1
  • 1
Mikhail Antonov
  • 1,297
  • 3
  • 21
  • 29