Spring Framework

Spring Environment란?

Junuuu 2023. 8. 9. 00:01
반응형

개요

Spring을 활용하다 보면 local, dev, prod 등 다양한 환경들을 사용하게 됩니다.

이때 환경별로 다르게 처리하고 싶은 경우에 Profile("local"), Profile("dev"), Profile("prod")등을 활용할 수 있지만 이렇게 되면 3가지의 클래스가 생겨나게 됩니다.

Spring Environment를 활용하여 이를 제어할 수 있습니다.

 

Spring Environment란?

package org.springframework.core.env;

public interface Environment extends PropertyResolver {
	String[] getActiveProfiles();
	String[] getDefaultProfiles();
	@Deprecated
	boolean acceptsProfiles(String... profiles);
	boolean acceptsProfiles(Profiles profiles);
}

org.springframework.core.env 패키지에 속하며 현재 애플리케이션이 실행 중인 환경을 나타내는 인터페이스입니다.

애플리케이션 환경의 두 가지 주요 측면인 profile와 properties를 다룹니다.

Properties에 관한 접근은 상위 인터페이스인 PrepertyResolver를 통해 다루어집니다.

getActiveProfiles()를 통해 활성화 중인 Profile의 정보들을 가져올 수 있습니다.

 

예를 들어 다음과 같이 활용할 수 있습니다.

@Component
@RequiredArgsConstructor
public class QASupporter {
	private final Environment environment;

	public boolean isProd(){
		boolean isEnvironmentProd = Arrays.asList(environment.getActiveProfiles()).contains("prod");
		return isEnvironmentProd
	}
}

Environment Bean을 주입받고, 현재 활성화된 Profiles리스트에 Prod가 포함되는지 체크합니다.

 

 

 

MockEnvironment

Environment의 테스트를 목적으로 사용되는 클래스입니다.

class QaSupporterTest {

    MockEnvironment environment = new MockEnvironment();
    QASupporter qASupporter = new QASupporter(environment);

    @ParameterizedTest
    @ValueSource(strings = {"local","dev","beta"})
    public void envLocalTest(String value){
        environment.addActiveProfile(value);

        boolean result = qASupporter.isProd();

        Assertions.assertFalse(result);
    }    
}

addActiveProfile()을 통해 Profile 환경을 추가할 수 있습니다.

이를 통해 테스트코드에서도 Environment가 포함된 코드를 검증할 수 있습니다.

 

 

 

 

참고자료

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html

 

Environment (Spring Framework 6.0.10 API)

Determine whether one or more of the given profiles is active — or in the case of no explicit active profiles, whether one or more of the given profiles is included in the set of default profiles. If a profile begins with '!' the logic is inverted, meani

docs.spring.io

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/mock/env/MockEnvironment.html

 

MockEnvironment (Spring Framework 6.0.10 API)

 

docs.spring.io