Initialize the S3Client as a Spring Bean. This allows you to inject the client wherever you need to interact with AWS.
Store your bucket details and credentials in src/main/resources/application.properties . For production, it is safer to use IAM roles or environment variables. properties download file from s3 bucket java spring boot
@RestController @RequestMapping("/api/files") public class FileController { private final S3Service s3Service; public FileController(S3Service s3Service) { this.s3Service = s3Service; } @GetMapping("/download/{fileName}") public ResponseEntity download(@PathVariable String fileName) { byte[] data = s3Service.downloadFile(fileName); return ResponseEntity.ok() .contentType(MediaType.APPLICATION_OCTET_STREAM) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") .body(data); } } Use code with caution. Best Practices for S3 Downloads Initialize the S3Client as a Spring Bean
: For very large files (GBs), avoid loading the entire byte array into memory. Use s3Client.getObject(request) to get an InputStream and stream it directly to the OutputStream of the HTTP response. For production, it is safer to use IAM
Add the AWS S3 SDK to your pom.xml file. Using the Bill of Materials (BOM) ensures version compatibility across AWS services.
: Never hardcode credentials in your source code. Use AWS Secrets Manager or Instance Profiles.
AWS Access Key and Secret Key with s3:GetObject permissions. A Spring Boot project (Java 17+ recommended). 1. Add Dependencies