개요
이미지를 저장과 호출을 위해 알고리즘(?)을 설계했지만 입출력 및 유저와 기본 배경 이미지를 테스트를 하면서 코드가 이쁘지 않다는 생각이 들어 구조를 변경하려 했다.
구조
변경 전
DirService는 DB가 아닌 특정 폴더에 이미지를 저장하기 위한 클래스이고 저장이 완료되면 img의 경로를 db에 저장하려고 했다. 하지만 폴더에 저장하는 단계와 db에 저장하는 단계를 나누면서 좀 더 복잡해졌기에 하나의 서비스에 몰아넣었다. 코드의 간결성을 중요하게 생각하기에 따로 메인과 유저 이미지를 폴더에 저장할 수 있도록 인터페이스를 설계하여 구분 지어 주었다.

변경 후

리펙토링
ImageUploadService -> ImageService <<interface>> 전
@Service
public class ImageUploadService {
private static final String defaultLocation = "E:\\img" + File.separator;
@Autowired
private UserApiService userService;
@Autowired
private UserBackGroundImgService backGroundImgService;
public void saveImageInDir(FileDTO fileDTO) {
String location = defaultLocation + fileDTO.getUsername();
Path path = Paths.get(location);
String originalName = fileDTO.getMultipartFile().getOriginalFilename();
long fileSize = fileDTO.getFileSize();
if (Files.isExecutable(path) == false) {
try {
Files.createDirectories(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
InputStream inputStream = fileDTO.getMultipartFile().getInputStream();
Path dirPath = path.resolve(fileDTO.getMultipartFile().getOriginalFilename());
Files.copy(inputStream, dirPath, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
// TODO: handle exception
}
//backGroundImgService.userImageSave();
}
}
interface
public interface ImageService {
static String DEFAULT_PATH = "E:\\img" + File.separator;
void saveImageInDir(FileDTO filedto);
Resource findBackGroundImageInDir(String originalName, String folderName);
boolean deleteBackGroundImageInDir(Long id);
}
리펙토링 후
@Override
public void saveImageInDir(FileDTO fileDTO) {
String location = DEFAULT_PATH + fileDTO.getUsername();
Path path = Paths.get(location);
if (Files.isExecutable(path) == false) {
try {
Files.createDirectories(path);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
InputStream inputStream = fileDTO.getMultipartFile().getInputStream();
Path dirPath = path.resolve(fileDTO.getMultipartFile().getOriginalFilename());
Files.copy(inputStream, dirPath, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
// TODO: handle exception
}
}
PS
리펙토링은 어떤 식으로 정리해야 할지 감이 잡히지 않는다. 계속적인 리펙토링은 하고 있지만 마음에 들지 않는다... 계속해야 할 듯하다.
'문제해결 및 코드 만들기' 카테고리의 다른 글
| [문제해결] Redis 사용 시 발생했던 Pageable 에러 문제 (0) | 2022.06.07 |
|---|---|
| [문제해결?] ehcache.xml 설정 중 발생했던 오류 (0) | 2022.06.02 |
| [문제 고민] jpa 쿼리 생성 기능에 따른 속도 차이 ? (0) | 2022.05.17 |
| [문제해결] 반복된 요청 쿼리문을 줄일 수 있을까 (0) | 2022.05.15 |
| [문제해결] AWS 스프링 빌드 중 발생한 문제점 (0) | 2022.05.13 |