-
spring yml/yaml/properties 파일 작동 안됨 오류 해결법spring 2024. 11. 6. 12:06
문제
application.yml 파일에 키값을 넣어놓고 .class파일로 가져오려고 했는데 가져오지 못하는 문제가 발생했다.
- application.yml / application.yaml 파일
api: key: aaaaaaaaaaa
- application.properties 파일
api.key=aaaaaaaaaaa
- 키값을 가져오려는 .java 파일
public class ClaudeConfig { @Value("${api.key}") private String secretKey; public ClaudeConfig() { System.out.println(secretKey) } }
- 출력 결과
null
원인
문제 원인은 @Value 애노테이션 때문이었다.
@Value는 @Value를 포함한 클래스가 생성된 이후 작동하는 특징이 있다. 그래서 클래스의 생성자가 실행된 이후에 키값을 가져온다. @Value가 작동하기 이전에 키값을 출력해서 null이 나왔던 것이다.
해결
- 수정된 .java 파일
public class ClaudeConfig { private String secretKey; public ClaudeConfig(@Value("${api.key}") String secretKey) { this.secretKey = secretKey; System.out.println(this.secretKey); } }
- 출력 결과
aaaaaaaaaaa
'spring' 카테고리의 다른 글
intelliJ에서 .env 파일 적용법 (1) 2025.01.29 [spring boot] 도커 사용시 DevTools 적용하기 (0) 2025.01.05 [spring boot] QueryDSL 세팅하기 (0) 2025.01.03 [spring boot] 'Parameter 0 of constructor in ~ ', 'Consider defining a bean of type ~' 오류 해결 (0) 2024.11.20 react와 spring boot 간 연동하기 / 통신하기 (0) 2024.11.07