我正在尝试通过电子邮件进行帐户验证。我创建了一个名为 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());
}
}
我有一个 Controller ,所以我可以测试一些东西。具有以下获取请求:
@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
@RestController
public class Application {
@Autowired
private ApplicationEventPublisher eventPublisher;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@GetMapping("/register")
public String registerNewUser() {
eventPublisher.publishEvent(new OnRegistrationSuccessEvent(new User(), "http://localhost"));
return "success";
}
@PostConstruct
public void init() {
eventPublisher.publishEvent(new OnRegistrationSuccessEvent(new User(), "http://localhost"));
}
}
class OnRegistrationSuccessEvent extends ApplicationEvent {
private String appUrl;
private User user;
public OnRegistrationSuccessEvent(User user, String appUrl) {
super(user);
this.user = user;
this.appUrl = appUrl;
}
}
@Component
class RegistrationEmailListener implements ApplicationListener<OnRegistrationSuccessEvent> {
public void onApplicationEvent(OnRegistrationSuccessEvent event) {
System.out.println("confirmed");
}
}
class User{
private String userName;
}
日志:
2019-05-29 09:01:59.259 INFO 62832 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-05-29 09:01:59.525 INFO 62832 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-05-29 09:01:59.529 INFO 62832 --- [ restartedMain] com.barath.app.Application : Started Application in 2.904 seconds (JVM running for 3.815)
2019-05-29 09:02:07.341 INFO 62832 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-05-29 09:02:07.341 INFO 62832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-05-29 09:02:07.349 INFO 62832 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
confirmed
关于java - 当我创建事件时,实现 ApplicationListener 接口(interface)的类不会启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56352591/