我已根据本教程http://www.baeldung.com/registration-verify-user-by-email
在我的Spring应用中完成了用户注册电子邮件确认有一个奇怪的问题。由于未知原因,我的自定义事件总是被触发2次。
这是代码: 的事件:
public class OnRegistrationCompleteEvent extends ApplicationEvent {
private final String appUrl;
private final Locale locale;
private final User user;
public OnRegistrationCompleteEvent(User user, Locale locale, String appUrl) {
super(user);
this.user = user;
this.locale = locale;
this.appUrl = appUrl;
}
public String getAppUrl() {
return appUrl;
}
public Locale getLocale() {
return locale;
}
public User getUser() {
return user;
}
}
监听器:
@Component
public class RegistrationListener implements ApplicationListener<OnRegistrationCompleteEvent> {
private final static Logger logger = LogManager.getLogger(RegistrationListener.class.getName());
@Autowired
private JavaMailSender mailSender;
@Override
public void onApplicationEvent(OnRegistrationCompleteEvent event) {
this.confirmRegistration(event);
}
private void confirmRegistration(OnRegistrationCompleteEvent event) {
logger.info("OnRegistrationCompleteEvent confirmSocialPosting fired");
final User user = event.getUser();
String recipientAddress = user.getEmail();
String subject = "Registration Confirmation";
String from = "contactblablabla@gmail.com";
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(mimeMessage, false, "utf-8");
String htmlMsg = "Your account was successfully registered! <br><br>" +
"username: "+user.getUsername()+"<br>"+
"password: "+user.getPassword()+"<br>";
mimeMessage.setContent(htmlMsg, "text/html");
helper.setTo(new InternetAddress(recipientAddress));
helper.setSubject(subject);
helper.setFrom(new InternetAddress(from));
mailSender.send(mimeMessage);
} catch (MessagingException e) {
logger.error("Message creation exception: "+e.getMessage());
}
}
}
控制器:
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public JsonResponse AddUser(@RequestBody @Valid User user, WebRequest request) throws SQLException {
String result = userService.RegisterUser(user);
if(result.equals("done")) {
try {
String appUrl = request.getContextPath();
eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user, request.getLocale(), appUrl));
} catch (Exception me) {
return new JsonResponse("FAIL", "Unknown on event publishing: "+ me.getMessage());
}
return new JsonResponse("OK", "");
} else if(result.equals("duplicate")) {
return new JsonResponse("FAIL", "duplicate");
}
return new JsonResponse("FAIL", "Unknown");
}
所以,在我的日志中,我有OnRegistrationCompleteEvent confirmSocialPosting fired
次2次。并发送2封电子邮件。可能是什么问题?
答案 0 :(得分:1)
这是因为它要注册两次。您在应用程序中使用了anotation,即base-package =&#34; com.example&#34; 这就是为什么它注册twise
从侦听器类中删除anotation @component并在.xml文件中定义bean defination
这是个傻瓜!!