본문 바로가기
기술도서/자바스프링 개발자를 위한 실용주의 프로그래밍

자바스프링 개발자를 위한 실용주의 11. 알아두면 유용한 스프링 활용법

by jasNote 2024. 11. 9.

타입 기반 주입

spring에서 DI는 타입 기반으로 주입을 한다. 인터페이스를 구현한 구현체가 여러개 있을 때, 콜렉션 형태의 인터페이스를 DI하도록 선언하면 관련 bean들이 콜렉션에 주입된다.

 

자세한 설명은 코드로 대체한다.

 

public interface NotificationChannel {

    boolean supports(Account account);

    void notify(Account account, String message);
}

@Component
public class EmailNotificationChannel implements NotificationChannel {
    @Override
    public boolean supports(Account account) {
        return account.getNotificationType() == NotificationType.EMAIL;
    }

    @Override
    public void notify(Account account, String message) {
        log.info("[Email] {} : {}", account.getName(), message);
    }
}

@Component
public class SlackNotificationChannel implements NotificationChannel {
    @Override
    public boolean supports(Account account) {
        return account.getNotificationType() == NotificationType.SLACK;
    }

    @Override
    public void notify(Account account, String message) {
        log.info("[Slack] {} : {}", account.getName(), message);
    }
}

 

@Service
@RequiredArgsConstructor
public class NotificationService {

	// EmailNotificationChannel과 SlackNotificationChannel이 주입됨.
    private final List<NotificationChannel> notificationChannels;

    public void notify(Account account, String message){
        for(NotificationChannel notificationChannel : notificationChannels){
            if(notificationChannel.supports(account)){
                notificationChannel.notify(account, message);
            }
        }
    }
}

 

자가 호출

 

자가 호출은 다음과 같다. 한 클래스에 두개의 함수가 있다. 한 함수가 또 다른 함수를 호출하는 형태를 자가호출이라고 한다. 

spring의 aop는 프록시 형태로 작동한다. 같은 클래스 내에서 함수를 호출하게 되면 프록시 객체를 타지 않기 때문에 aop가 작동하지 않는다.

 

과거 정리한 내용이 있어서 링크로 대체한다. https://jas-note.tistory.com/111