【问题标题】:SpringBoot : ServletContext resource cannot resolve S3 URLSpringBoot:ServletContext 资源无法解析 S3 URL
【发布时间】:2019-08-10 14:59:19
【问题描述】:

我正在开发一个 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。

【问题讨论】:

    标签: java spring-boot servlets amazon-s3 spring-cloud-aws


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      使用“java -jar”和“mvn spring-boot:run”启动应用程序是有区别的。来自 Spring Boot 文档:“Spring Boot Maven 插件包含一个运行目标,可用于快速编译和运行您的应用程序。应用程序以分解形式运行,就像在您的 IDE 中一样”。这可能是问题的原因。

      【讨论】:

        猜你喜欢
        • 2019-03-06
        • 1970-01-01
        • 1970-01-01
        • 2015-04-30
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多