我正在开发一个 Spring Boot 应用程序,其中集成了 Amazon S3 服务。
这个类是我访问 S3 存储桶的存储库:
public class S3FileRepository implements ImageRepository {
private String bucket;
private AmazonS3 s3Client;
private ResourceLoader resourceLoader;
public S3FileRepository(ResourceLoader resourceLoader, AmazonS3 s3Client, String bucket) {
this.resourceLoader = resourceLoader;
this.s3Client = s3Client;
this.bucket = bucket;
}
private static String toS3Uri(String bucket, String imageName) {
return String.format("s3://%s/%s", bucket, imageName);
}
@Override
public Resource getImage(String name) {
return resourceLoader.getResource(S3FileRepository.toS3Uri(this.bucket, name).concat(this.IMAGE_EXTENSION));
}
使用 Spring Boot Autoconfiguration按照建议。
因此,在我的 pom.xml
中,除其他外,我还
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-aws-autoconfigure</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-aws-context</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
此外,我有一个 application.properties
这样做:
cloud.aws.credentials.accessKey= (mykey)
cloud.aws.credentials.secretKey= (mysecret)
cloud.aws.credentials.instanceProfile=true
cloud.aws.region.static=eu-west-2
cloud.aws.stack.auto=false
问题:
如果我编译我的项目,然后我只需使用 java -jar target/myproject.jar
运行 JAR,一切都会正常工作,我会正确获取我要求的图像,一切都很好。
相反,如果我在尝试时使用IDE默认值运行项目mvn spring-boot:run
获取图像(存在于存储桶中)发生异常,内容如下:
ServletContext resource [/s3://mybucket/test.jpeg] cannot be resolved to URL because it does not exist
java.io.FileNotFoundException: ServletContext resource [/s3://mybucket/test.jpeg] cannot be resolved to URL because it does not exist
所以我认为是它抛出异常,因为它就像它进入 jar 来寻找与s3://mybucket/匹配的东西test.jpeg
但我不明白为什么,以及为什么它只使用 mvn spring-boot:run
运行项目而不运行 jar。
最佳答案
您可能会遇到 spring-cloud-aws
问题 #384因此,当您从 IDE 启动应用程序时激活的 spring-boot-devtools
依赖项会在资源加载中激活不同的代码路径。
您可以通过从 pom.xml
文件中删除 spring-boot-devtools
依赖项、在 IDE 中重新加载项目来测试是否遇到此问题,并运行相同的测试。
关于java - SpringBoot : ServletContext resource cannot resolve S3 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55251912/