카테고리 없음

내 주석 @Value는 사용 중이고 구성 요소 주석이 달린 클래스로 호출되는 경우에도 null을 반환합니다.

기록만이살길 2021. 2. 22. 13:14
반응형

내 주석 @Value는 사용 중이고 구성 요소 주석이 달린 클래스로 호출되는 경우에도 null을 반환합니다.

1. 질문(문제점):

저는 Spring을 처음 사용하고 도움이 필요합니다. 하드 코딩하는 대신 application.properties를 사용하여 하나의 API 키를 설정하고 싶지만 항상 null을 반환합니다. IntelliJ는 파일에 설정 한 값으로 올바르게 평가합니다. 나는 이미 여기에서 다른 질문을 읽었으며 거의 ​​모든 솔루션은 Spring이 Components, Beans 등과 같은 관리되는 클래스에 이러한 값 주석을 "주입"할 수 있다고 말합니다. 그게 내가 한 일이고 여전히 null을 얻었습니다! 다른 모든 것이 내가 의도 한대로 작동합니다. 어떤 방향으로도 감사합니다!

내 application.properties

api.someapiservice.key=08e...f

속성 값을 사용하는 클래스 :

@Component
public class ApiClient implements ApiClientInterface {

@Value("${api.someapiservice.key}")
private String API_KEY;

public ApiClient () {
    System.out.println(API_KEY); //Returns null after spring log info: Initialized JPA EntityManagerFactory for persistence unit 'default'
    ...
}

ApiClient를 사용하는 클래스 :

@Component
public class SomeService {

private final SomeRepository someRepository;
private final ApiClient apiClient;

public PlaylistService(SomeRepository someRepository , ApiClient apiClient ) {
    this.SomeRepository = SomeRepository;
    this.apiClient = ApiClient;
}

2. 해결방안:

필드 주입은 인스턴스가 이미 생성 될 때까지 발생할 수 없으므로 생성자에서 필드 @Value(또는 @Autowired)는 항상 null이됩니다. @Value대신 생성자 매개 변수로를 이동하십시오 .

65877929
반응형