[java] Guice를 사용한 파일 업로드/다운로드 처리

많은 웹 애플리케이션에서 파일 업로드 및 다운로드는 필수적인 기능입니다. Java에서는 Guice를 사용하여 파일 업로드 및 다운로드를 처리하는 것이 간편하고 효율적입니다. 이번 글에서는 Guice를 사용하여 파일 업로드 및 다운로드를 처리하는 방법에 대해 알아보겠습니다.

1. 의존성 주입 설정

먼저, 파일 업로드 및 다운로드 관련 의존성 주입을 설정해야 합니다. Guice에서는 Module을 통해 의존성을 관리합니다.

public class FileModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(FileUploader.class).to(FileUploaderImpl.class);
        bind(FileDownloader.class).to(FileDownloaderImpl.class);
        // 다른 의존성 주입 설정
    }
}

위 코드에서 FileUploaderFileDownloader는 파일 업로드 및 다운로드를 처리하는 인터페이스입니다. FileUploaderImplFileDownloaderImpl 클래스는 해당 인터페이스를 구현한 클래스입니다.

2. 파일 업로드 처리

파일 업로드를 처리하기 위해서는 FileUploader 인터페이스를 사용해야 합니다. FileUploader 인터페이스는 다음과 같이 정의될 수 있습니다.

public interface FileUploader {
    void upload(File file, String destination);
}

FileUploaderImpl 클래스는 FileUploader 인터페이스를 구현하며, 파일 업로드를 실제로 처리합니다. 다음은 파일 업로드 처리 예제입니다.

@Inject
private FileUploader fileUploader;

public void handleFileUpload() {
    File file = new File("/path/to/file");
    String destination = "/upload/destination";
    fileUploader.upload(file, destination);
}

위 예제에서 FileUploader 인터페이스의 구현체가 @Inject 애너테이션을 통해 주입됩니다. 주입된 FileUploader 인스턴스를 사용하여 파일을 업로드할 수 있습니다.

3. 파일 다운로드 처리

파일 다운로드를 처리하기 위해서는 FileDownloader 인터페이스를 사용해야 합니다. FileDownloader 인터페이스는 다음과 같이 정의될 수 있습니다.

public interface FileDownloader {
    void download(String source, OutputStream outputStream);
}

FileDownloaderImpl 클래스는 FileDownloader 인터페이스를 구현하며, 파일 다운로드를 실제로 처리합니다. 다음은 파일 다운로드 처리 예제입니다.

@Inject
private FileDownloader fileDownloader;

public void handleFileDownload() {
    String source = "/path/to/file";
    OutputStream outputStream = new FileOutputStream("/download/destination");
    fileDownloader.download(source, outputStream);
}

위 예제에서도 FileDownloader 인터페이스의 구현체가 @Inject 애너테이션을 통해 주입됩니다. 주입된 FileDownloader 인스턴스를 사용하여 파일을 다운로드할 수 있습니다.

4. 파일 업로드/다운로드 기능 사용

위에서 정의한 파일 업로드 및 다운로드 기능을 웹 애플리케이션에서 사용하려면 Guice Injector를 통해 의존성을 주입해야 합니다.

public class AppServlet extends HttpServlet {
    @Inject
    private FileUploader fileUploader;
    
    @Inject
    private FileDownloader fileDownloader;
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 파일 업로드 처리
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 파일 다운로드 처리
    }
}

위 예제에서 AppServlet 클래스에 FileUploaderFileDownloader 인스턴스가 @Inject 애너테이션을 통해 주입됩니다. 이제 필요에 따라 파일 업로드 및 다운로드 처리 로직을 구현할 수 있습니다.

이처럼 Guice를 사용하여 파일 업로드 및 다운로드를 처리할 수 있습니다. Guice의 의존성 주입 기능을 통해 코드의 유연성과 재사용성을 향상시킬 수 있습니다. 자세한 내용을 확인하려면 Guice 문서를 참조하세요.

참고 자료