如何将 Google json 密钥文件配置为 Spring 核心资源?

How to config Google json key file as Spring core Resource?

我正在 Spring 中开发 Spring 引导应用程序 8. 我正在尝试获取 Google 凭据 json 文件作为 spring核心资源对象,但它不工作。我进行了调试,发现 serviceAccountKey 为空,因为 @Value("${google.service.account.key}") 只加载路径而不是文件。有人可以告诉我如何处理这个吗?实在不知道怎么直接加载json密钥文件

代码如下:

GoogleDriveServiceImpl

@Service
public class GoogleDriveServiceImpl implements GoogleDriveService {
    @Value("${google.service.account.key}")
    private Resource serviceAccountKey;

private Drive createDrive() throws IOException, GeneralSecurityException {
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(ServiceAccountCredentials.fromStream(serviceAccountKey.getInputStream())
            .createScoped(DriveScopes.all()));
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
            .setApplicationName("external").build();
    }
}

Application.properties 文件

google.service.account.key=H:\document\googleKey\***********.json
server.port=8867

经过进一步研究,我找到了一种将 JSON 密钥文件加载为 spring 核心资源对象的方法:我没有使用直接路径,而是使用 类路径 @Value 中的前缀和 将 JSON 密钥文件移动到资源文件夹 .

代码如下:

GoogleDriveServiceImpl 类

@Service
public class GoogleDriveServiceImpl implements GoogleDriveService {

    // Move the JSON key file into resource/google
    @Value("classpath:google/********.json")
    private Resource serviceAccountKey;

private Drive createDrive() throws IOException, GeneralSecurityException {
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(ServiceAccountCredentials.fromStream(serviceAccountKey.getInputStream())
            .createScoped(DriveScopes.all()));
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();

    return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
            .setApplicationName("external").build();
    }
}