我正在做一個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,