1、事件类
@Getter
public class StudentEvent extends ApplicationEvent {
private Student student;
public StudentEvent(Object source,Student student) {
super(source);
this.student = student;
}
}
2、ApplicationEventPublisher的publishEvent来发布事件
@Service
public class UserEventRegister {
@Autowired
private ApplicationEventPublisher publisher;
public void register() throws Exception {
//注册用户
Student student=new Student();
student.setId(1);
student.setName(LocalDateTime.now().toString());
publisher.publishEvent(new StudentEvent(this,student));
}
}
3、使用@EventListener来监听事件
@Component
public class UserEventListener {
@EventListener(value = "StudentEvent.class" ,condition = "#user.name!=null")
public void handleEvent(StudentEvent studentEvent) throws Exception{
System.out.println(studentEvent.getName());
System.out.println(studentEvent.getSex());
}
}
或
@Service
public class StudentEventService implements ApplicationListener<StudentEvent> {
@Override
public void onApplicationEvent(StudentEvent studentEvent) {
System.out.println("邮件服务接到通知,给 " + studentEvent.getSource() + " 发送邮件...");
}
}