【发布时间】: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