jeudi 21 février 2019

Create interface using Generics with different parameters in Java

I am building a rest service for file uploading and I have different file upload options as different controller methods.

This is my controller FileUploadController:

@RestController
public class FileUploadController {
    private static final String PATH_SEPARATOR = "/";
    private final FileUploadToS3Service fileUploadToS3Service;

    @Autowired
    public FileUploadController(FileUploadToS3Service fileUploadToS3Service) {
        this.fileUploadToS3Service = fileUploadToS3Service;
    }

    @GetMapping("/file-upload-to-s3")
    @ResponseBody
    public UploadResult uploadFileToS3Bucket(@Valid @RequestBody FileUploadToS3BucketRequest request) {
        return fileUploadToS3Service.uploadFileToS3Bucket(request.getBucketName(), request.getPathToUpload(), request.getFile());
    }

    @GetMapping("/file-url-upload-to-s3")
    @ResponseBody
    public UploadResult uploadFileFromUrlToS3Bucket(@Valid @RequestBody FileUrlUploadToS3BucketRequest request) {
        return fileUploadToS3Service.uploadFileUrlToS3Bucket(request.getBucketName(), request.getPathToUpload(), request.getFileUrl());
    }
}

This is FileUploadToS3Service interface:

public interface FileUploadToS3Service {
    UploadResult uploadFileToS3Bucket(String bucketName, String pathToUpload, File fileToUpload);

    UploadResult uploadFileUrlToS3Bucket(String bucketName, String pathToUpload, String fileUrlToUpload);
}

This is the service implementation FileUploadToS3ServiceImpl:

public interface FileUploadToS3Service {
    UploadResult uploadFileToS3Bucket(String bucketName, String pathToUpload, File fileToUpload);

    UploadResult uploadFileUrlToS3Bucket(String bucketName, String pathToUpload, String fileUrlToUpload);
}

My question is about making this service more generic to be make it extendable easily in the future. In the most basic approach I will create another interface and another implementation likes FileUploadToAnotherService and FileUploadToAnotherServiceImpl if another uploading api is integrated and the methods will have different parameters.

I assume that the clients will use the same methods with different upload locations. I thought about creating a common interface for these lets say FileUploadService instead of FileUploadToS3 interface and implement this for each different type of uploading strategy. However, I could not figure out how I will implement the methods with different parameters.

Looking forward to your helps. Thanks!

Aucun commentaire:

Enregistrer un commentaire