Design and Implementation of a Flexible Download Library for Spring Applications
This article explains how to build a Spring‑based download library that uses annotations to simplify downloading files, HTTP resources, or custom objects, supports both WebMvc and WebFlux, handles concurrency, compression, and event‑driven logging, and provides a modular architecture for extensibility.
Downloading files is a common yet often cumbersome requirement in many projects; the author created a library to simplify this by allowing a single annotation to handle various download sources such as classpath files, local files, HTTP URLs, and custom objects.
The library introduces @Download and @GetMapping annotations, enabling developers to return data objects (e.g., a list of devices) while the framework automatically resolves file names and sources via @SourceObject and @SourceName annotations.
To support both traditional Servlet (WebMvc) and reactive (WebFlux) environments, the implementation wraps request/response handling in a reactive Mono<ServerHttpResponse> and provides a ReactiveDownloadHolder to access the current request and response without blocking.
The core architecture uses a DownloadContext that travels through a chain of DownloadHandler steps, allowing flexible insertion of operations such as source loading, caching, and compression. Sources are abstracted as Source objects with factories like FileSourceFactory and HttpSourceFactory to create appropriate handlers based on the input type.
Concurrent loading of remote resources is achieved via a SourceLoader interface, enabling custom thread‑pool or scheduler strategies. After loading, files are compressed using a pluggable SourceCompressor (e.g., ZIP) and written to the response through a unified DownloadWriter abstraction that works for both servlet and reactive streams.
Response writing is handled by adapting OutputStream to reactive FluxSink via ReactiveDownloadResponse , ensuring byte[] data can be streamed correctly in WebFlux. Event publishing with DownloadEventPublisher and listeners provides extensible logging for each step, including progress updates and timing metrics.
The article also discusses pitfalls such as context destruction in WebFlux, the need for explicit doAfterTerminate handling, and differences between servlet and reactive response APIs.
Overall, the library offers a highly extensible, annotation‑driven solution for file download, compression, and streaming in Spring applications, reducing boilerplate code and improving developer productivity.
Top Architecture Tech Stack
Sharing Java and Python tech insights, with occasional practical development tool tips.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.