spring @Value无法正确生成值,正在获取null

oxiaedzo  于 2022-11-21  发布在  Spring
关注(0)|答案(2)|浏览(133)

当我运行代码时,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
zaqlnxep

zaqlnxep1#

您的代码片段并不完全清楚这一点,但我猜测您的DataBucketUtil没有被示例化为Bean,因此没有填充@Value注解字段。有关@Value注解的更多详细信息,请参见here
您可以使用@Component@Service注解将类转换为服务或组件,然后将其自动连接到所需位置。有关Bean的更多信息,请参见here

swvgeqrz

swvgeqrz2#

请添加注解。我希望它能工作。

@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;

/** ............ **/

}

相关问题