IoC 컨테이너 (3) : Environment

de_sj_awa·2021년 6월 25일

8. Environment

ApplicationContext는 BeanFactory 기능 외에도 다양한 기능을 한다. 그중에서도 EnvironmentCapable이라는 기능이 있다.

public interface ApplicationContext
extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory, MessageSource, ApplicationEventPublisher, ResourcePatternResolver

EnvironmentCapable프로파일프로퍼티를 다루는 인터페이스이다.

ApplicationContext extends EnvironmentCapable

  • getEnvironment()

1. 프로파일

프로파일

  • 빈들의 그룹
  • Environment의 역할은 활성화할 프로파일 확인 및 설정

프로파일 유즈케이스

  • 테스트 환경에서는 A라는 빈을 사용하고, 배포 환경에서는 B라는 빈을 쓰고 싶다.
  • 이 빈은 모니터링 용도니까 테스트할 때는 필요가 없고 배포할 때만 등록이 되면 좋겠다.

테스트 환경, 프로덕션 환경, 스테이징 환경에서는 특정한 환경에서 어떤 빈을 쓰겠다고 지정할 수 있다.

@Component
public class AppRunner implements ApplicationRunner {
    @Autowired
    ApplicationContext ctx;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Environment environment = ctx.getEnvironment();
        //System.out.println(Arrays.toString(environment.getActiveProfiles()));
        //System.out.println(Arrays.toString(environment.getDefaultProfiles()));
    }
}

EnvironmentCable의 getEnvironment() 메서드를 사용할 수 있다.

프로파일 정의하기

  • 클래스에 정의
    - @Configuration @Profile(“test”)
    - @Component @Profile(“test”)
  • 메소드에 정의
    - @Bean @Profile(“test”)
public class TestBookRepository implements BookRepository{
}
@Configuration
//@Profile("test")
public class TestConfiguration {

    @Bean
    @Profile("test")
    public BookRepository bookRepository(){
        return new TestBookRepository();
    }
}

이 빈 설정파일은 TestProfile Environment일때만 사용할 수 있다.

프로파일 설정하기

  • -Dspring.profiles.avtive=”test,A,B,...”
  • @ActiveProfiles (테스트용)

프로파일 표현식

  • ! (not)
  • & (and)
  • | (or)
@Repository
@Profile("!prod")
public class TestBookRepository implements BookRepository{

}

2. 프로퍼티

프로퍼티

  • 다양한 방법으로 정의할 수 있는 설정값
  • Environment의 역할은 프로퍼티 소스 설정 및 프로퍼티 값 가져오기

프로퍼티에는 우선 순위가 있다.

  • StandardServletEnvironment의 우선순위
    - ServletConfig 매개변수
    - ServletContext 매개변수
    - JNDI (java:comp/env/)
    - JVM 시스템 프로퍼티 (-Dkey=”value”)
    - JVM 시스템 환경 변수 (운영 체제 환경 변수)

프로퍼티 값 가져오는 방법

@Component
public class AppRunner implements ApplicationRunner {
    @Autowired
    ApplicationContext ctx;

    @Autowired
    BookRepository bookRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Environment environment = ctx.getEnvironment();
        System.out.println(environment.getProperty("app.name"));
    }
}

아니면 체계적으로 properties 파일을 만들 수 있다.

@SpringBootApplication
@PropertySource("classpath:/app.properties")
public class Springtest4Application {

    public static void main(String[] args) {

        SpringApplication.run(Springtest4Application.class, args);
    }
}

그렇다면 Properties 파일과 JVM properties로 넘겨준 값 중에 어떤 것이 더 우선순위가 높은가? JVM Properties가 우선순위가 더 높다.

또한 스프링부트에서는 다음과 같은 것도 가능하다.

@Component
public class AppRunner implements ApplicationRunner {
    @Autowired
    ApplicationContext ctx;

    @Autowired
    BookRepository bookRepository;

    @Value("${app.name}")
    String appName;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Environment environment = ctx.getEnvironment();
        System.out.println(environment.getProperty("app.name"));
        System.out.println(appName);
    }
}

참고

  • 인프런 : 스프링 프레임워크 핵심 기술(백기선)
profile
이것저것 관심많은 개발자.

0개의 댓글