SpringBoot:ServletContext 资源无法解析 S3 URL

SpringBoot : ServletContext resource cannot resolve S3 URL

我正在开发一个 Spring 启动应用程序,我在其中集成了 Amazon S3 服务。
这个 class 是我访问 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 default 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。

使用 "java -jar" 和 "mvn spring-boot:run" 启动应用程序之间存在差异。来自 Spring 引导文档:"The Spring Boot Maven plugin includes a run goal that can be used to quickly compile and run your application. Applications run in an exploded form, as they do in your IDE"。这可能是问题的原因。

您可能遇到了 spring-cloud-aws 问题 #384,因此当您从 IDE 启动应用程序时激活的 spring-boot-devtools 依赖项会激活一个不同的资源加载中的代码路径。

您可以通过从 pom.xml 文件中删除 spring-boot-devtools 依赖项、在 IDE 和 运行 中重新加载项目来测试是否遇到此问题同样的测试。