When I run the code the external configuration in the application.properties file does not get populated into the variable within the DataBucketUtil. I'm sure I'm doing something stupid,but I can not find out wheres the problem.
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");
}
My application properties is given below:
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
CodePudding user response:
It is not entirely clear from your code snippet but my guess would be that your DataBucketUtil
is not instantiated as a Bean and therefore the @Value
annotated fields are not populated. See here for more details about the @Value
annotation.
You could transform your class to a service or component with the @Component
or @Service
annotation and then autowire it to where you need it. See here for more information about beans.
CodePudding user response:
Please add Annotations. I hope it work.
@EnableConfigurationProperties
@Component
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;
/** ............ **/
}