【问题标题】:Run another function when an annotated method is called调用带注释的方法时运行另一个函数
【发布时间】:2016-05-04 10:53:15
【问题描述】:

有没有办法创建自定义或使用现有的注释来触发代码在调用带注释的方法时运行?最好是使用 Spring 库。

例如:

@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);
}

【问题讨论】:

  • 为什么不直接从doSomething 内部调用sendEmail
  • sendMail 将被系统中具有不同模板的各种类中的多个方法使用。我的想法是,我可以避免在每个类中声明/自动装配sendMails 的类,以防止混乱或引用静态方法
  • 好吧,我唯一能想到的就是 interseptors,但我不知道这是否可行。
  • 这帮助我找到了正确的方向,谢谢!调查 inteceptors 让我了解 Spring AOP 和这个 blog post,这似乎是我需要的。谢谢!
  • 很高兴我能帮上忙 :)

标签: java spring annotations


【解决方案1】:
@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
    }
}

【讨论】:

猜你喜欢
  • 2018-02-23
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多