![](/img/trans.png)
[英]How to get the classpath resource basename of a config file in Spring proejct?
[英]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.