I'm converting a small Spring method to Micronaut. The purpose of this method is to write a byte array to a destination in the cloud. To identify the destination, a URI is passed as argument to the Spring method. This is the implementation using Spring:
public class MyWriter{
public MyWriter(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public boolean writeToDestination(String uri, byte[] bytes) {
WritableResource resource = (WritableResource) resourceLoader.getResource(uri);
try (OutputStream out = resource.getOutputStream()) {
out.write(bytes);
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
throw new WriteFileException(e);
}
return true;
}
}
Based on this question, I know that Micronaut doesn't have the org.springframework.core.io.Resource
class, but it has io.micronaut.core.io.ResourceLoader
and other variants. I have not found any Micronaut alternative to org.springframework.core.io.WritableResource
.
I have come across io.micronaut:micronaut-cli:2.0.0.M2
, which apparently includes a similar implementation to the Spring classes Resource and WritableResource, but every time I use that I get this error:
Failed to inject value for parameter [resourceLoader] of class: ResourceManager
Message: No bean of type [io.micronaut.cli.io.support.ResourceLoader] exists.
I am new to Micronaut, so I am not familiar with most IO features it offers.
That being said, how do I convert the method above to Micronaut?
If it's cloud storage specifically, you should try using Micronaut Object Storage.
Eg: Install dependencies for your cloud provider
<dependency>
<groupId>io.micronaut.objectstorage</groupId>
<artifactId>micronaut-object-storage-aws</artifactId>
<version>1.1.0</version>
</dependency>
Set configuration options - src/main/resources/application-ec2.yml
micronaut:
object-storage:
aws:
default:
bucket: profile-pictures-bucket
Inject in your controllers/services/etc. a bean of type ObjectStorageOperations, the parent interface that allows you to use the API in a generic way for all cloud providers.
And use:
public String saveProfilePicture(String userId, Path path) {
UploadRequest request = UploadRequest.fromPath(path, userId);
UploadResponse<?> response = objectStorage.upload(request);
return response.getKey();
}
All info above is from: Micronaut Object Storage.