【发布时间】:2019-10-14 14:17:02
【问题描述】:
我正在尝试通过电子邮件进行帐户验证。我创建了一个名为OnRegistrationSuccessEvent 的事件类,它代表成功注册的事件。
我创建了一个监听器来处理这个名为 RegistrationEmailListener 的事件。
这是两个类的代码:
OnRegistrationSuccessEvent 类。
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 类。
@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());
}
}
我有一个控制器,所以我可以测试一下。带有以下获取请求:
@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 是什么样子的:
@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;
}
日志:
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.]
【问题讨论】:
-
确保您的侦听器位于
@SpringBootApplication的组件扫描覆盖的包中。我怀疑它没有被检测到。 -
原来是这样。谢谢。
标签: java spring spring-boot spring-mvc jakarta-ee