我正在开发一个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
我认为的原因是它引发了一个异常,因为它就像进入罐子一样,寻找与s3://mybucket/test.jpeg
相匹配的内容,但我可以无法了解为什么以及为什么会发生,仅使用mvn spring-boot:run
运行项目而不运行jar。
答案 0 :(得分:3)
您很可能遇到spring-cloud-aws
问题#384,因此从IDE启动应用程序时激活的spring-boot-devtools
依赖关系会在资源加载中激活不同的代码路径。
您可以通过从spring-boot-devtools
文件中删除pom.xml
依赖项,在IDE中重新加载项目并运行相同的测试来测试是否遇到此问题。
答案 1 :(得分:0)
应用程序使用“ java -jar”启动和“ mvn spring-boot:run”启动之间有区别。来自Spring Boot文档:“ Spring Boot Maven插件包含一个运行目标,可用于快速编译和运行您的应用程序。应用程序以爆炸形式运行,就像在IDE中一样”。这可能是问题的原因。