Код: Выделить всё
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Код: Выделить всё
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
@Configuration
public class S3Config {
@Value("${region}")
private String region;
@Value("${accessKey}")
private String accessKey;
@Value("${secretKey}")
private String secretKey;
@Bean
S3Client s3Client() {
AwsBasicCredentials credentials = AwsBasicCredentials.create(accessKey, secretKey);
return S3Client.builder()
.credentialsProvider(StaticCredentialsProvider.create(credentials))
.region(Region.of(region))
.build();
}
}
Код: Выделить всё
package com.example.demo.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import com.example.demo.services.S3Service;
public class S3Controller {
@Autowired
private S3Service s3Service;
@GetMapping("/listAllObjects")
public ResponseEntity viewObjects() {
return new ResponseEntity(s3Service.listObjects(),HttpStatus.OK);
}
}
Код: Выделить всё
package com.example.demo.services;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListObjectsResponse;
import software.amazon.awssdk.services.s3.model.S3Object;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class S3Service {
@Value("${bucketName}")
private String bucketName;
private final S3Client s3Client;
public S3Service(S3Client s3Client) {
this.s3Client = s3Client;
}
public List listObjects() {
ListObjectsResponse listObjectsResponse = s3Client.listObjects(b -> b.bucket(bucketName));
return listObjectsResponse.contents().stream()
.map(S3Object::key)
.collect(Collectors.toList());
}
}
Код: Выделить всё
spring.application.name=demo
aws.region=`${region}`
aws.accessKey=`${accessKey}`
aws.secretKey=`${secretKey}`
aws.bucketName=`${bucketName}`
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
Подробнее здесь: https://stackoverflow.com/questions/783 ... g-bean-wit