DS's TechBlog
[Spring] AWS S3 + Spring Boot 3.2 설정 및 적용하기 본문
배경
웹 프로젝트에서 이미지를 AWS S3에 저장하기로 했습니다. Spring Boot 3과 함께 AWS S3를 사용하는 법에 대해서 구글링 해봤지만, 오래된 버전에 대한 내용만 나와있어서 글을 작성하게 되었습니다.
AWS IAM, AWS S3 버킷은 생성했다고 가정합니다.
종속성 추가
https://github.com/awspring/spring-cloud-aws?tab=readme-ov-file
GitHub - awspring/spring-cloud-aws: The New Home for Spring Cloud AWS
The New Home for Spring Cloud AWS. Contribute to awspring/spring-cloud-aws development by creating an account on GitHub.
github.com
위 링크에서 Spring 버전에 따른 spring-cloud-aws 버전을 알 수 있습니다.
저는 Spring Boot 3.2, Spring Framework 6.1을 사용하므로 build.gradle에 아래와 같이 종속성을 추가했습니다.
implementation 'io.awspring.cloud:spring-cloud-aws-starter-s3:3.1.1'
설정 정보
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
spring.cloud.aws.credentials.access-key=${AWS_IAM_ACCESS_KEY}
spring.cloud.aws.credentials.secret-key=${AWS_IAM_SECRET_KEY}
spring.cloud.aws.region.static=ap-northeast-2
spring.cloud.aws.s3.bucket=${AWS_S3_BUCKET_NAME}
application.properties 파일에 위와 같이 작성했습니다.
- spring.servlet.multipart.max-file-size=10MB: 업로드할 수 있는 개별 파일의 최대 크기를 정의합니다.
- spring.servlet.multipart.max-request-size=10MB: 전체 요청의 최대 크기를 정의합니다. 즉, 하나의 요청으로 전송할 수 있는 모든 파일의 총합 크기입니다.
- spring.cloud.aws.credentials.access-key=${AWS_IAM_ACCESS_KEY}: AWS S3에서 발급 받은 Access key Id입니다.
- spring.cloud.aws.credentials.secret-key=${AWS_IAM_SECRET_KEY}: AWS S3에서 발급 받은 Secret access key입니다.
- spring.cloud.aws.region.static=ap-northeast-2: 애플리케이션이 AWS 아시아 태평양(서울) 리전을 사용하도록 설정
- spring.cloud.aws.s3.bucket=${AWS_S3_BUCKET_NAME}: S3에서 생성한 버킷의 이름을 작성하면 됩니다. 위의 설정 정보들과 다르게, 특정 라이브러리에 포함되어 있는 것이 아닙니다. 다른 이름으로 사용하셔도 무방합니다.
Access Key, Secret Key, Bucket Name은 위와같이 환경변수로 설정하여 주입받는 것이 보안상 안전합니다.
업로드 예제
@RequiredArgsConstructor
@RestController
public class TestController {
private final S3Operations s3Operations;
@PostMapping("/test/upload")
public ResponseEntity<?> uploadFile(@RequestBody MultipartFile multipartFile) {
try (InputStream inputStream = multipartFile.getInputStream()) {
s3Operations.upload("버킷 이름", "S3에 저장할 경로", inputStream,
ObjectMetadata.builder().contentType(multipartFile.getContentType()).build());
} catch (IOException e) {
throw new RuntimeException(e);
}
return ResponseEntity.ok().build();
}
}
S3Operations는 S3Client를 한 단계 더 추상화 한 인터페이스입니다. S3Template가 이를 구현합니다.
이를 통해서 간단하게 AWS S3에 upload 및 download를 할 수 있습니다.
- "버킷 이름"에는 설정 정보의 spring.cloud.aws.s3.bucket를 이용하면 됩니다.
- "S3에 저장할 경로"에는 Key를 저장하게 됩니다. 여기서 Key란 파일의 경로와 이름을 결합한 문자열로, S3 버킷 내에서 파일을 식별하는 데 사용됩니다. ex) "profiles/user1234/profile.jpg"
결과
Postman으로 요청을 보낸 후, AWS S3를 확인하면 설정한 key로 파일이 저장된 것을 볼 수 있습니다.
이렇게 Spring Boot 3.2에서 AWS S3를 사용하는 방법에 대해서 간단히 알아보았습니다. 많은 분들에게 도움이 되었으면 좋겠습니다. 읽어주셔서 감사합니다.
참고 자료
https://docs.awspring.io/spring-cloud-aws/docs/3.1.1/reference/html/index.html#spring-cloud-aws-s3
Spring Cloud AWS
Secrets Manager helps to protect secrets needed to access your applications, services, and IT resources. The service enables you to easily rotate, manage, and retrieve database credentials, API keys, and other secrets throughout their lifecycle. Spring Clo
docs.awspring.io
'Java & Spring' 카테고리의 다른 글
[Spring Data JPA] 이미지 파일과 DB 간의 일관성 유지하기 With @TransactionalEventListener - 2 (0) | 2025.01.05 |
---|---|
[Spring Data JPA] 이미지 파일과 DB 간의 일관성 유지하기 with SQL Order Based on Foreign Key Constraints - 1 (1) | 2024.12.27 |
[Spring Security] authorizeHttpRequests 우선순위 적용하기 (0) | 2024.05.17 |
[Spring] Swagger default 200 response 삭제하기 (0) | 2024.05.03 |
[Spring] Swagger 공통 응답 코드 처리 및 Enum으로 정의한 응답 코드 사용하기 (0) | 2024.05.03 |