簡體   English   中英

如何將 Google json 密鑰文件配置為 Spring 核心資源?

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

I'm developing a Spring boot application in Java 8. I'm trying to get the Google credential json file as spring core Resource object but it is not working. 我已經調試並看到serviceAccountKey 是 null 因為 @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

After further research I have found a way to load JSON key file as spring core Resource object: Instead of use direct path, I'm using the classpath preflix in @Value and move the JSON key file into resource folder .

這是代碼:

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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM