但是,有時數據庫中會包含來自生產的數據,并且存在在電子郵件測試執行期間向真實客戶發送電子郵件的風險。
這篇文章將解釋如何避免在沒有在發送電子郵件功能中明確編寫代碼的情況下避免這種情況。
我們將使用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 don't 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