Я пытаюсь проверить аккаунт по электронной почте.Я создал класс событий с именем OnRegistrationSuccessEvent
, который представляет событие успешной регистрации.Я создал слушатель для обработки этого события под названием RegistrationEmailListener
.Это код для двух классов:
OnRegistrationSuccessEvent
class.
public class OnRegistrationSuccessEvent extends ApplicationEvent {
private String appUrl;
private User user;
public OnRegistrationSuccessEvent(User user, String appUrl) {
super(user);
this.user = user;
this.appUrl = appUrl;
}
// gettes and setters
}
RegistrationEmailListener
class.
@Component
public class RegistrationEmailListener implements ApplicationListener<OnRegistrationSuccessEvent> {
@Autowired
private IUserService userService;
@Autowired
private MailSender mailSender;
private static Logger logger = Logger.getLogger(RegistrationEmailListener.class.getName());
public void onApplicationEvent(OnRegistrationSuccessEvent event) {
logger.info("The rehistraton success event is fired up.");
try {
this.confirmRegistration(event);
} catch (SendingEmailFailureException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
}
private void confirmRegistration(OnRegistrationSuccessEvent event) throws SendingEmailFailureException {
User user = event.getUser();
String token = UUID.randomUUID().toString();
userService.createVerficationToken(user, token);
String recipent = user.getEmail();
String subject = "Registration confirmation";
String url = event.getAppUrl() + "/confirmRegistration?token=" + token;
String message = "Thank you for regestring in our Tourists web app. Please click on the link below to complete your registration: ";
SimpleMailMessage email = new SimpleMailMessage();
email.setTo(recipent);
email.setSubject(subject);
email.setText(message + "http://localhost:8080" + url);
mailSender.send(email);
logger.info("Registration >>> Activation email is sent");
logger.info("Recipient >>> " + recipent);
logger.info("Text >>> " + email.getText());
}
}
И у меня есть cntroller, поэтому яможет проверить вещи.со следующим запросом get:
@GetMapping("/register")
public String registerNewUser(WebRequest request) {
User user = new User("bilal", "basiliusmourk@gmail.com", passwordEncoder.encode("bilal"), new Date());
try {
user.addAuthoriry(authorityService.getAuthority(AuthorityType.ROLE_TOURIST));
} catch (EntityNotFoundException e) {
logger.info(e.getMessage());
}
try {
userService.registerNewUserAccount(user);
} catch (UsernameAlreadyExistsException e) {
logger.info(e.getMessage());
} catch (EmailAlreadyExistsException e) {
logger.info(e.getMessage());
}
String appUrl = request.getContextPath();
logger.info("app url >>> " + appUrl);
logger.info("publishing OnRegistrationSuccessEvent");
eventPublisher.publishEvent(new OnRegistrationSuccessEvent(user, appUrl));
//autoAuthentication(context, user.getUsername(), "bilal");
logger.info("registration process completed for: " + user.getUsername());
return "registrationSuccess";
}
Я убедился, что OnRegistrationSuccessEvent
действительно создан.Проблема в том, что слушатель не знает, что событие запущено, и я не уверен, почему.если кто-нибудь может помочь, я буду благодарен.
Редактировать: и вот как выглядят мои бины в классе конфигурации:
@Bean(name = "mailSender")
public MailSender javaMailService() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setProtocol("smtp");
javaMailSender.setUsername("myEmail");
javaMailSender.setPassword("myPassword");
Properties mailProperties = new Properties();
mailProperties.put("mail.smtp.auth", true);
mailProperties.put("mail.smtp.starttls.enable", true);
mailProperties.put("mail.smtp.debug", true);
javaMailSender.setJavaMailProperties(mailProperties);
return javaMailSender;
}
@Bean
public MessageSource messageSource() {
final ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages");
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setCacheSeconds(0);
return messageSource;
}
logs:
Hibernate: insert into user_authority (user_id, authority_id) values (?, ?)
2019-05-29 04:03:54 DEBUG AbstractCollectionPersister:384 - Done inserting collection: 1 rows inserted
2019-05-29 04:03:54 DEBUG JdbcCoordinatorImpl:183 - HHH000420: Closing un-released batch
2019-05-29 04:03:54 DEBUG ThreadPoolAsynchronousRunner:236 - com.mchange.v2.async.ThreadPoolAsynchronousRunner@78ae34f7: Adding task to queue -- com.mchange.v2.resourcepool.BasicResourcePool$1RefurbishCheckinResourceTask@1f15b10c
2019-05-29 04:03:54 DEBUG BasicResourcePool:1801 - trace com.mchange.v2.resourcepool.BasicResourcePool@23b62cc3 [managed: 5, unused: 4, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@63544e3b)
2019-05-29 04:03:54 INFO Class:98 - app url >>> /pfa-web-v2
2019-05-29 04:03:54 INFO Class:99 - publishing OnRegistrationSuccessEvent
2019-05-29 04:03:54 INFO Class:105 - registration process completed for: bilal
2019-05-29 04:03:57 DEBUG ThreadPoolAsynchronousRunner:778 - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@692fae76 -- Running DeadlockDetector[Exiting. No pending tasks.]
2019-05-29 04:04:07 DEBUG ThreadPoolAsynchronousRunner:778 - com.mchange.v2.async.ThreadPoolAsynchronousRunner$DeadlockDetector@692fae76 -- Running DeadlockDetector[Exiting. No pending tasks.]