2015-11-11 68 views
0

我正在做一個Spring MVC web應用程序,然後我想發送一封電子郵件給新的註冊用戶以確認/激活目的。然後我編寫一個ApplicationEvent和ApplicationListener類。問題在於,偵聽器會調用兩次,所以我收到2封電子郵件,並且在我的數據庫中有2個令牌字符串。ApplicationListener被調用兩次

如何解決這個問題?下面

代碼,

了ApplicationEvent:

public class OnRegistrationSuccessEvent extends ApplicationEvent { 

    private String appUrl; 
    private Locale locale; 
    private User user; 

    public OnRegistrationSuccessEvent(String appUrl, Locale locale, User user) { 
     super(user); 
     this.appUrl = appUrl; 
     this.locale = locale; 
     this.user = user; 
    } 

    // getters, setters 
} 

ApplicationListener:

@Component 
public class RegistrationListener implements ApplicationListener<OnRegistrationSuccessEvent> { 

    @Autowired 
    UserService userService; 

    @Autowired 
    MessageSource messages; 

    @Autowired 
    JavaMailSender javaMailSender; 

    @Override 
    public void onApplicationEvent(OnRegistrationSuccessEvent event) { 
     this.confirmationEmail(event); 
    } 

    private void confirmationEmail(OnRegistrationSuccessEvent event){ 
     // register token in DB, send mail 
    } 

    private SimpleMailMessage buildEmailMessage(OnRegistrationSuccessEvent event, User user, String token) { 
     //build some message 
    } 
} 

我調用事件在@Controller:

eventPublisher.publishEvent(new OnRegistrationSuccessEvent(URL, request.getLocale(), user)); 

謝謝用於h elp,

回答

0

假設publishEventApplicationEventPublisher#publishEvent與其中一個內置ApplicationContext子類型的實現,那麼它將只調用onApplicationEvent一次。

我認爲你正在經歷的是有多個RegistrationListener對象。 ApplicationContext會將發佈到它的任何事件傳播到其父上下文。我相信你在每個根和servlet應用程序上下文中都有一個RegistrationListener bean。看看你的配置,弄清楚發生了什麼。 (您也可以登錄this(或內RegistrationListener一些代表實例的唯一)證實了這一點。)

如何解決這個問題呢?

將您的配置更改爲僅在您的所有ApplicationContext s中生成並註冊一個Listener