SpringEvent���¼�����
��������
��Spring��ʹ��Spring Event���¼�������һ��ʵ�������������Ч��ʽ�����Ѿ�������Spring Event�Ļ��������ʵ�ֲ��裬�������ҽ�ͨ������Ĵ���ʾ������ϸ���������Spring��ʵ���¼��������ơ�
����һ�������¼�
���ȣ�������Ҫ����һ���¼��࣬�������Ҫ�̳�ApplicationEvent
����������У����ǿ��Է�װ���¼���ص����ݡ�
1 | import org.springframework.context.ApplicationEvent; |
�����������RegisterSuccessEvent
���װ��һ���û�ע��ɹ����¼������а������û�����Ϣ��
������������¼�������
��������������Ҫ����һ���¼����������¼���������Ҫʵ��ApplicationListener
�ӿڣ�����Ҳ����ʹ��@EventListener
ע�������һ��������Ϊ�¼���������
ʹ��ApplicationListener
�ӿڣ�
1 | import org.springframework.context.ApplicationListener; |
����ʹ��@EventListener
ע�⣺
1 | import org.springframework.context.event.EventListener; |
ע�⣺ʹ��@EventListener
ע��ʱ�����ϣ�������ض����͵��¼���������ע����ָ���¼����ͣ������������������ʡ�������ͣ�����ζ�������Լ����������͵��¼�������ͨ�����ǻ�ָ��������¼���������ߴ���������ȺͿɶ��ԣ���
�������������¼�
���������Ҫ�ں��ʵĵط������¼�����ͨ������ij��ҵ�����������֮����еġ�
1 | import org.springframework.beans.factory.annotation.Autowired; |
�����������UserService
���е�registerUser
�������û�ע��ɹ�����һ��RegisterSuccessEvent
�¼���
�ܽ�
ͨ�����ϲ��裬���Ǿ���Spring��ʵ����һ�����¼��������ơ���UserService
�е�registerUser
����������ʱ�����ᷢ��һ��RegisterSuccessEvent
�¼���Ȼ������ע��������¼����͵ļ��������ᱻ֪ͨ������ִ����Ӧ�Ĵ����������ַ�ʽ������ʵ�������Ľ�����������ơ�
������
��Spring����У�����������¼�����������ǿ��Ĺ��ܣ����ǿ��Զ���ʹ�ã���Ҳ���Խ�������������ض���ҵ������@TransactionalEventListener
ע���������һ����ϵ㣬������������������IJ�ͬ�������ڽμ�������Ӧ�¼���
��������
����Transaction���������ݿ�����У�������ָ��Ϊ������������Ԫִ�е�һϵ�в�������Щ����Ҫôȫ��ִ�У�Ҫôȫ����ִ�С��������ĸ����ԣ�ԭ���ԣ�Atomicity����һ���ԣ�Consistency���������ԣ�Isolation�����־��ԣ�Durability����ͨ�����ΪACID���ԡ�
�¼�������Event Listening������Spring����У��¼��������������������ߣ������¼����������������������첽��ͬ���ؽ��ղ�������Щ�¼�������һ�ֽ��������ͨ�ŵķ�ʽ��
@TransactionalEventListener
��ʹ��
�����ṩ��ʾ���У�UserService
�������û�ע����������ע��ɹ���һ��UserRegistrationEvent
�¼�������¼���UserRegistrationEventListener
���������ؼ����ڼ�����ʹ����@TransactionalEventListener
ע�⣬����ζ���¼��Ĵ�������������ض��ν��С�
Ĭ����Ϊ��
@TransactionalEventListener
Ĭ��������ɹ��ύ��AFTER_COMMIT
�Σ������¼�������������Ϊ��ȷ���������еIJ�������Ӱ�쵽����Ļع����ߡ����磬���ͻ�ӭ�ʼ������IJ����Ͳ�Ӧ��Ӱ���û�ע������ijɹ����phase������ͨ��
phase
���ԣ��������ü�����������IJ�ͬ�δ�����BEFORE_COMMIT
���������ύǰ���������������������ʱִ��һЩ�������������������׳��쳣�����ܵ�������ع���AFTER_COMMIT
��������ɹ��ύ����������ִ�в���ع��IJ������緢��֪ͨ��AFTER_ROLLBACK
��������ع����������ڼ�¼�ع���־��ִ������������AFTER_COMPLETION
����������ɺ��������ύ���ǻع���������ִ�����������صIJ�����
Ӧ�ó���
ʹ��@TransactionalEventListener
�ĵ��ͳ���������
- ������ɹ���ִ���첽�������緢���ʼ�������֪ͨ�ȣ��Ա��������������ִ�С�
- ������ع���ִ���ض����������¼�������Ա��ڹ����Ų����ơ�
- �������ύǰִ��һЩ�����������ݸ��²�����
��֮��@TransactionalEventListener
�ṩ��һ�����ķ�ʽ��������IJ�ͬ����Ӧ�¼����Ӷ�ʵ�ָ����ӵ�ҵ�����������Ľ���ͨ�š�