2017-12-16 7 views
0

내 Spring MVC (Spring Boot가 아닌) 어플리케이션을 Firebase에 연결하려고합니다. 내 응용 프로그램의 폴더 구조는 다음과 같습니다Spring MVC로 Firebase ServiceAccount json 리소스를 올바르게로드하는 방법은 무엇입니까?

folder structure

문제는 내가 어디에 자원 및 메소드 호출의 올바른 순서를로드하는 방법은 API 키 JSON 파일을 배치 할 위치를 알 수 없다는 것입니다.

아래에 표시된 방법으로 리소스로드를 시도했습니다. 그 전에도 ClassLoader를 사용하여 WEB-INF 폴더에서로드하려고 시도했지만 작동했지만 코드를 변경하고 InputStream에 대해 NullPointer Exception (왜 FileNotFound 예외가 아닌가?)을 받았고 이전 상태를 복원 할 수 없었습니다.

"Spring MVC load resource"를 얼마나 많이 검색했는지에 관계없이 리소스를로드 할 수 없기 때문에 FileNotFound 예외를 계속 수신하며 디버거에 서비스 계정의 "init"메소드를 @PostConstruct가 서버 시작시 실행 중이 아닙니다.

자원을로드하고 작동하게하려면 "초기화"메소드를 호출 할 수 있어야한다는 것을 알고 있습니다. (bean을 생성하고 firebase 메소드를 사용하기 전에 한 번 호출하는 것만으로 충분할 것이라고 생각합니다.)하지만 저는 구현 된 구현을 만들 수 없습니다.

는 여기에서 예를 사용 : https://github.com/savicprvoslav/Spring-Boot-starter (페이지 하단)

내 컨트롤러 클래스 :

@Controller 
@RequestMapping("/firebase") 
public class FirebaseController { 

    @Autowired 
    private FirebaseService firebaseService; 

    @GetMapping(value="/upload/maincategories") 
    public void uploadMainRecordCategories() { 

     firebaseService.uploadMainRecordCategories(); 
    } 

내 서비스 클래스 :

@Service 
public class FirebaseServiceBean implements FirebaseService { 

    @Value("/api.json") 
    Resource apiKey; 

@Override 
public void uploadMainRecordCategories() { 
    // do something 
} 

    @PostConstruct 
    public void init() { 

     try (InputStream serviceAccount = apiKey.getInputStream()) { 

      FirebaseOptions options = new FirebaseOptions.Builder() 
        .setCredentials(GoogleCredentials.fromStream(serviceAccount)) 
        .setDatabaseUrl(FirebaseStringValue.DB_URL).build(); 

      FirebaseApp.initializeApp(options); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

답변

0

방법에 값을 저장하는 방법에 대한 @Value ("$ {firebase.apiKey}")를 사용하면 스프링 속성을 사용할 수 있습니까?

대안으로, 속성 및 참조 파일 경로를 저장하는 것이 @Value()에있어서 application.properties

@Value("${service.account.path}") 
private String serviceAccountPath; 

:

service.account.path = /path/to/service-account.json 

다음 설정 코드 :

private String getAccessToken() throws IOException { 
    GoogleCredential googleCredential = GoogleCredential 
      .fromStream(getServiceAccountInputStream()) 
      .createScoped(Collections.singletonList("https://www.googleapis.com/auth/firebase.messaging")); 
    googleCredential.refreshToken(); 
    return googleCredential.getAccessToken(); 
} 

private InputStream getServiceAccountInputStream() { 
    File file = new File(serviceAccountPath); 
    try { 
     return new FileInputStream(file); 
    } catch (FileNotFoundException e) { 
     throw new RuntimeException("Couldn't find service-account.json"); 
    } 
} 
관련 문제