javascript
aspect spring_使用Aspect和Spring Profile进行电子邮件过滤
aspect spring
在Web應(yīng)用程序開(kāi)發(fā)期間,經(jīng)常需要發(fā)送電子郵件。但是,有時(shí)數(shù)據(jù)庫(kù)中會(huì)包含來(lái)自生產(chǎn)的數(shù)據(jù),并且存在在電子郵件測(cè)試執(zhí)行期間向真實(shí)客戶發(fā)送電子郵件的風(fēng)險(xiǎn)。
這篇文章將解釋如何避免在沒(méi)有在發(fā)送電子郵件功能中明確編寫(xiě)代碼的情況下避免這種情況。
我們將使用兩種技術(shù):
我假設(shè)您已經(jīng)在項(xiàng)目中設(shè)置了Profiles,并專注于Aspect方面。
在該示例中,發(fā)送電子郵件的類是EmailSender,其發(fā)送方法如下所示:
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 } } 現(xiàn)在,我們將添加防止在未在生產(chǎn)中運(yùn)行代碼的客戶發(fā)送電子郵件的邏輯。
為此,我們將使用Aspects,這樣我們就不必在send方法中編寫(xiě)它,從而可以保持關(guān)注點(diǎn)分離的原則。
創(chuàng)建一個(gè)將包含過(guò)濾方法的類:
@Aspect @Component public class EmailFilterAspect {public EmailFilterAspect() {} }然后創(chuàng)建一個(gè)PointCut來(lái)捕獲send方法的執(zhí)行:
@Pointcut("execution(public void com.mycompany.util.EmailSender.send(..))")public void sendEmail(){}由于我們需要控制是否應(yīng)執(zhí)行該方法,因此需要使用Arround批注。
@Around("sendEmail()") public void emailFilterAdvice(ProceedingJoinPoint proceedingJoinPoint){try {proceedingJoinPoint.proceed(); //The send email method execution} catch (Throwable e) { e.printStackTrace();} }最后一點(diǎn),我們需要訪問(wèn)send方法的輸入?yún)?shù)(即獲取EmailEntity)并確認(rèn)我們沒(méi)有在開(kāi)發(fā)中向客戶發(fā)送電子郵件。
@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();}} } 而已。
關(guān)于配置,您需要在項(xiàng)目中包括縱橫圖罐。
在Maven中,它看起來(lái)像這樣:
在您的spring應(yīng)用程序配置xml文件中,您需要具有以下內(nèi)容:
祝好運(yùn)!
參考:來(lái)自Gal Levinsky博客博客的JCG合作伙伴 Gal Levinsky 使用Aspect和Spring Profile進(jìn)行電子郵件過(guò)濾 。
翻譯自: https://www.javacodegeeks.com/2012/07/email-filtering-using-aspect-and-spring.html
aspect spring
總結(jié)
以上是生活随笔為你收集整理的aspect spring_使用Aspect和Spring Profile进行电子邮件过滤的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JLBH示例1 –为什么应在上下文中对代
- 下一篇: gradle idea java ssm