做网站定位,网站 建设 申请,石景山 网站建设,上海工商网上服务大厅在Web应用程序开发期间#xff0c;经常需要发送电子邮件。 但是#xff0c;有时数据库中会包含来自生产的数据#xff0c;并且存在在电子邮件测试执行期间向真实客户发送电子邮件的风险。 这篇文章将解释如何避免在没有在发送电子邮件功能中明确编写代码的情况下避免这种情… 在Web应用程序开发期间经常需要发送电子邮件。 但是有时数据库中会包含来自生产的数据并且存在在电子邮件测试执行期间向真实客户发送电子邮件的风险。 这篇文章将解释如何避免在没有在发送电子邮件功能中明确编写代码的情况下避免这种情况。 我们将使用2种技术 Spring Profiles –一种指示运行环境是什么的机制即开发生产.. AOP –简而言之它是一种以解耦的方式在方法上编写附加逻辑的机制。 我假设您已经在项目中设置了Profiles并专注于Aspect方面。 在该示例中发送电子邮件的类是EmailSender其发送方法如下所示 public class EmailSender {
//empty default constructor is a must due to AOP limitation
public EmailSender() {}//Sending email function
//EmailEntity - object which contains all data required for email sending (from, to, subject,..)
public void send(EmailEntity emailEntity) {
//logic to send email
}
} 现在我们将添加防止在未在代码上运行代码的客户发送电子邮件的逻辑。 为此我们将使用Aspects因此我们不必在send方法中编写它从而可以保持关注点分离的原则。 创建一个包含过滤方法的类 Aspect
Component
public class EmailFilterAspect {public EmailFilterAspect() {}
} 然后创建一个PointCut来捕获send方法的执行 Pointcut(execution(public void com.mycompany.util.EmailSender.send(..)))public void sendEmail(){} 由于我们需要控制是否应执行该方法因此需要使用Arround批注。 Around(sendEmail())
public void emailFilterAdvice(ProceedingJoinPoint proceedingJoinPoint){try {proceedingJoinPoint.proceed(); //The send email method execution} catch (Throwable e) { e.printStackTrace();}
} 最后一点我们需要访问send方法的输入参数即获取EmailEntity并确认我们没有在开发中向客户发送电子邮件。 Around(sendEmail())public void emailFilterAdvice(ProceedingJoinPoint proceedingJoinPoint){//Get current profile
ProfileEnum profile ApplicationContextProvider.getActiveProfile();Object[] args proceedingJoinPoint.getArgs(); //get input parametersif (profile ! ProfileEnum.PRODUCTION){//verify only internal mails are allowedfor (Object object : args) {if (object instanceof EmailEntity){String to ((EmailEntity)object).getTo();if (to!null to.endsWith(mycompany.com)){//If not internal mail - Dont continue the method try {proceedingJoinPoint.proceed();} catch (Throwable e) {e.printStackTrace();}}}}}else{//In production dont restrict emailstry {proceedingJoinPoint.proceed();} catch (Throwable e) {e.printStackTrace();}}
} 而已。 关于配置您需要在项目中包括纵横图罐。 在Maven中它看起来像这样 org.aspectjaspectjrt${org.aspectj.version}org.aspectjaspectjweaver${org.aspectj.version}runtime 在您的spring应用程序配置xml文件中您需要具有以下内容 祝好运 参考来自Gal Levinsky博客博客的JCG合作伙伴 Gal Levinsky 使用Aspect和Spring Profile进行电子邮件过滤 。 翻译自: https://www.javacodegeeks.com/2012/07/email-filtering-using-aspect-and-spring.html