Skip to content

Pojo 클래스에서 스프링 환경 변수 사용하기 #2

Open
@suna-ji

Description

@suna-ji

1. 문제 정의

상황 :

빈으로 관리되지 않는 POJO 클래스에서 스프링 환경변수를 사용해야 한다.

문제점:

@value는 Spring의 의존성 주입 어노테이션으로, Spring 컨테이너가 관리하는 Bean에서만 동작합니다.
Spring 컨테이너는 애플리케이션 구동 시점에 다음과 같은 단계를 거칩니다:

  • Bean 생성
  • 의존성 주입
  • 초기화 작업
    @valueBean의 생명주기와 연계되어 작동하며, 컨테이너가 Bean을 관리하고 처리하는 과정에서 필드나 메서드에 값을 주입합니다.
    POJO 클래스는 Spring 컨테이너의 관리 대상이 아니므로, @value 어노테이션을 인식하거나 처리할 수 없습니다.

2. 해결 방법

Application Context를 통해 Environment 가져오기

Spring의 ApplicaitonContext를 활용하여 환경 변수에 접근할 수 있습니다.
ApplicationContext를 주입받을 수 있는 헬퍼 클래스를 생성하고 POJO 클래스에서는 헬퍼클래스를 통해 Environment를 사용할 수 있습니다.

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextHelper implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }
}


import org.springframework.core.env.Environment;

public class MyPojo {

    public String getConfigValue() {
        Environment environment = SpringContextHelper.getContext().getBean(Environment.class);
        return environment.getProperty("my.config.value");
    }
}

3. 추가 정보: ApplicationContext와 ApplicationContextAware

ApplicationContextAware 인터페이스

ApplicationContextAware는 Spring Framework에서 제공하는 인터페이스로 Spring의 ApplicationContext 객체를 주입받을 수 있도록 지원합니다.
이를 구현한 클래스는 Spring 컨테이너에 의해 ApplicationContext가 전달됩니다.

ApplicationContext

ApplicationContext는 Spring 컨테이너의 핵심으로, 모든 Bean, 환경 변수, 프로파일 정보 등에 접근할 수 있습니다.

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions