101market / fast-grill-url

0 stars 0 forks source link

Spring의 Event EventListener #17

Open americanomin opened 2 years ago

americanomin commented 2 years ago

https://sunghs.tistory.com/139

의존성이 강한 로직의 레이어를 분리할 때 사용

https://sunghs.tistory.com/139

https://github.com/madvirus/ddd-start2/blob/969fb9e898671e963a6d74b09d057840987f064f/src/main/java/com/myshop/member/infra/PasswordChangedEventHandler.java

package com.myshop.member.infra;

import com.myshop.member.command.domain.PasswordChangedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class PasswordChangedEventHandler {
    @EventListener(PasswordChangedEvent.class)
    public void handle(PasswordChangedEvent event) {
        // 이메일 발송 코드
    }
}
package com.myshop.common.event;

import org.springframework.context.ApplicationEventPublisher;

public class Events {
    private static ApplicationEventPublisher publisher;

    static void setPublisher(ApplicationEventPublisher publisher) {
        Events.publisher = publisher;
    }

    public static void raise(Object event) {
        if (publisher != null) {
            publisher.publishEvent(event);
        }
    }
}
public void initializePassword() {
        String newPassword = generateRandomPassword();
        this.password = new Password(newPassword);
        Events.raise(new PasswordChangedEvent(id.getId(), newPassword));
    }