4

Is there a way to create a custom, or use an existing, annotation to trigger code to run when the annotated method is called? Preferably, I would like to use Spring libraries.

For example:

@SendEmail("templateName")
public void doSomething() {
    log.info("Something is happening");
}

public void sendEmail(String templateName) {
    // This method is called everytime doSomething() is called
    log.info("Sending email using template " + templateName);
}
SelketDaly
  • 539
  • 1
  • 5
  • 20
  • 1
    Why not just call `sendEmail` from inside `doSomething` ? – user3719857 May 04 '16 at 11:03
  • `sendMail` would be used by multiple methods in various classes in the system with different templates. My thinking behind this is that I would be able to avoid declaring/autowiring `sendMails`'s class in each of these classes, to prevent clutter or references to static methods – SelketDaly May 04 '16 at 11:09
  • 2
    Well the only thing I can think of is interseptors, but I don't know if that will work. – user3719857 May 04 '16 at 11:10
  • That helped get me in the right direction, thanks! Looking into inteceptors let me to Spring AOP and this [blog post](http://blog.javaforge.net/post/76125490725/spring-aop-method-interceptor-annotation), which seems to be what I need. Thanks! – SelketDaly May 04 '16 at 11:33
  • 1
    Glad I could help :) – user3719857 May 04 '16 at 13:41

1 Answers1

3
@Component
@Aspect
public class Mail {
    @After("execution (@com.yourdirectoryofyourcustomAnnotation.SendMail * *(..))")
    public void sendEmail(JointPoint jp){
        // it will send a mail after every method which tagged by your annotation
    }
}
erolkaya84
  • 1,769
  • 21
  • 28
  • It works for me! For other users read the documentation https://docs.spring.io/spring/docs/2.5.x/reference/aop.html – Angelo Dec 31 '19 at 09:06