当我运行代码时,www.example.com文件中的外部配置application.properties没有填充到DataBucketUtil中的变量中。我确信我做了一些愚蠢的事情,但我无法找出问题所在。
public class DataBucketUtil {
private static final Logger logger = LoggerFactory.getLogger(DataBucketUtil.class);
@Value("${gcp.config.file}")
private String gcpConfigFile;
@Value("${gcp.project.id}")
private String gcpProjectId;
@Value("${gcp.bucket.id}")
private String gcpBucketId;
@Value("${gcp.directory.name}")
private String gcpDirectoryName;
/**
* Upload file to GCS
*
* @param multipartFile-
* @param fileName-
* @param contentType-
* @return -
*/
public FileDto uploadFile(MultipartFile multipartFile, String fileName, String contentType) {
try {
logger.debug("Start file uploading process on GCS");
byte[] fileData = FileUtils.readFileToByteArray(convertFile(multipartFile));
InputStream inputStream = new ClassPathResource(gcpConfigFile).getInputStream();
StorageOptions options = StorageOptions.newBuilder().setProjectId(gcpProjectId)
.setCredentials(GoogleCredentials.fromStream(inputStream)).build();
Storage storage = options.getService();
Bucket bucket = storage.get(gcpBucketId, Storage.BucketGetOption.fields());
RandomString id = new RandomString(6, ThreadLocalRandom.current());
Blob blob = bucket.create(gcpDirectoryName + "/"
+ fileName + "-" + id.nextString() + checkFileExtension(fileName),
fileData, contentType);
if (blob != null) {
logger.debug("File successfully uploaded to GCS");
return new FileDto(blob.getName(), blob.getMediaLink());
}
} catch (IOException e) {
logger.error("An error occurred while uploading data. Exception: ", e);
throw new RuntimeException("An error occurred while uploading data to GCS");
}
throw new RuntimeException("An error occurred while uploading data to GCS");
}
我的应用程序属性如下:
gcp.config.file=gcp-config/gcs-prod-ho-finance.json
gcp.project.id=brac-main gcp.bucket.id=prod-ho-finance
gcp.dir.name=gs://prod-ho-finance
2条答案
按热度按时间zaqlnxep1#
您的代码片段并不完全清楚这一点,但我猜测您的
DataBucketUtil
没有被示例化为Bean,因此没有填充@Value
注解字段。有关@Value
注解的更多详细信息,请参见here。您可以使用
@Component
或@Service
注解将类转换为服务或组件,然后将其自动连接到所需位置。有关Bean的更多信息,请参见here。swvgeqrz2#
请添加注解。我希望它能工作。