java - 如何将 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
解决方案
经过进一步研究,我找到了一种将 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();
}
}
推荐阅读
- php - 客户端未经授权无法使用此方法检索访问令牌 - 致命错误
- php - 如何让 ovh 从 index.html 而不是 index.php 运行我的网站?
- html - 根据百分比设置 div 背景颜色(如进度条)
- python-3.x - 将csv转换为xlsx时,如何在xlsxwriter中保留一列数字作为字符串?
- haskell - 为计算机音乐应用程序和 Haskell 安装 Euterpea
- python - 蟒蛇 3 | 自动打开新的 .exe 窗口并在每一帧中获取他的位置
- swift - NSUnknownKeyExeption 使用 firebase 和 NSobject
- emacs - M-shift-RET 不会在 org-mode 中产生另一个 todo
- arrays - Ionic 3 - 通过另一个数组管道对数组进行排序?
- swift - 如何在 Swift 中阻止 UIScrollView 中的垂直滑动移动?