[java] Google Guice를 사용하여 이메일 발송하기

Google Guice는 자바 용도의 경량 의존성 주입(Dependency Injection) 프레임워크이며, 개발자들이 의존성 주입을 손쉽게 처리할 수 있도록 도와줍니다. 이번 예시에서는 Google Guice를 사용하여 이메일을 발송하는 방법에 대해 알아보겠습니다.

1. 의존성 주입 설정

먼저, Maven 등의 빌드 도구를 사용하여 Google Guice를 프로젝트에 추가해야 합니다. 이후 EmailModule 클래스를 생성하여 의존성 주입을 설정해 줍니다.

import com.google.inject.AbstractModule;
import javax.mail.Session;

public class EmailModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(Session.class).toProvider(EmailSessionProvider.class);
        bind(EmailSender.class);
    }
}

위 예시 코드에서 EmailModule 클래스는 AbstractModule을 상속받아 구현되었습니다. bind() 메서드를 사용하여 의존성을 설정하며, Session.classEmailSessionProvider 프로바이더로, EmailSender 클래스를 바인딩하도록 설정하였습니다.

2. 이메일 발송 기능 구현

이제 EmailSender 인터페이스와 해당 인터페이스를 구현한 EmailSenderImpl 클래스를 생성해 보겠습니다.

public interface EmailSender {
    boolean sendEmail(String recipient, String subject, String body);
}

public class EmailSenderImpl implements EmailSender {
    private final Session session;
    
    @Inject
    public EmailSenderImpl(Session session) {
        this.session = session;
    }
    
    @Override
    public boolean sendEmail(String recipient, String subject, String body) {
        // 이메일 발송 로직 구현
        return true;
    }
}

위 코드에서 EmailSender 인터페이스는 이메일 발송 기능을 추상화한 것이며, EmailSenderImpl 클래스는 EmailSender 인터페이스를 구현한 구체적인 클래스입니다. 생성자에 @Inject 어노테이션을 사용하여 의존성 주입을 설정하였습니다.

3. 의존성 주입 사용 예시

이제 의존성 주입이 설정된 이메일 발송 기능을 사용하는 코드를 작성해 보겠습니다.

import com.google.inject.Guice;
import com.google.inject.Injector;

public class Main {
    public static void main(String[] args) {
        Injector injector = Guice.createInjector(new EmailModule());
        EmailSender emailSender = injector.getInstance(EmailSender.class);
        
        String recipient = "example@example.com";
        String subject = "Test Email";
        String body = "This is a test email.";
        
        boolean result = emailSender.sendEmail(recipient, subject, body);
        if (result) {
            System.out.println("Email sent successfully.");
        } else {
            System.out.println("Failed to send email.");
        }
    }
}

위 예시 코드에서 Guice.createInjector() 메서드를 사용하여 EmailModule의 의존성 주입 설정을 로드하고, getInstance() 메서드를 사용하여 EmailSender 인스턴스를 가져옵니다. 그 후에는 해당 인스턴스를 사용하여 이메일을 발송하였습니다.

Google Guice를 사용하여 이메일 발송 기능을 구현하는 방법에 대해 알아보았습니다. Google Guice는 자바 개발에 많은 도움을 주는 강력한 의존성 주입 프레임워크이며, 이렇게 구현한 이메일 발송 기능을 다른 프로젝트에 유연하게 적용할 수 있습니다.

참고 자료