首页 > 解决方案 > 如何将 Google json 密钥文件配置为 Spring 核心资源?

问题描述

我正在使用 Java 8 开发 Spring Boot 应用程序。我正在尝试将 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

标签: javaspringspring-bootgoogle-drive-apigoogle-api-java-client

解决方案


经过进一步研究,我找到了一种将 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();
    }
}

推荐阅读