Spring

@Profile, @ActiveProfiles

ch-yang 2022. 12. 28. 00:24

@Profile

Spring Framework 공식 문서에서의 @Profile에 대한 설명이다.

[Spring Framework Doc]
It is often useful to conditionally enable or disable a complete @Configuration class or even individual @Bean methods, based on some arbitrary system state. One common example of this is to use the @Profile annotation to activate beans only when a specific profile has been enabled in the Spring Environment

@Configuration 클래스 또는 개별 @Bean 메서드를 조건부로 활성화 또는 비활성화하는 것은 종종 유용하다.
Spring 환경에서 @Profile 어노테이션을 사용하여 특정 profile이 활성화된 경우에만 Bean을 활성화 한다.

@Configuration
@Profile("development")
public class DevelopmentConfiguration {

    @Bean
    public DataSource dataSource() {
        // create and return a development DataSource
    }
}

위의 예제에서 dataSource Bean은 "development" profile이 활성화된 경우에만 생성되어 컨텍스트에 등록된다.
"development" profile의 활성화는 아래 예제와 같이 application.properties에서 설정할 수 있다.

#활성화 profile로 "development"를 설정
spring.profiles.active=development

#활성화 profile로 "development"와 "production"을 설정
spring.profiles.active=development,production

@ActiveProfiles

@ActiveProfiles 어노테이션은 스프링 테스트가 실행될 때 활성화되어야 하는 프로필을 지정하는데 사용된다.
이를 통해 기본 애플리케이션 구성을 수정하지 않고도 다양한 구성과 종속성을 테스트할 수 있다.

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
public class MyTest {
    // test code goes here
}

위의 예제에서는 @Profile("test") 어노테이션이 달린 Bean이 애플리케이션 컨텍스트에 등록된다.

@ActiveProfiles("test,production")

위와 같이 "test"와 "production" profile을 활성화 할 수도 있다.


참고로 나는 Test를 방해하는 Bean 이 있어 특정 Bean 만 비활성화하는 용도로 다음과같이 사용했다.

@Component
@Profile("!test") // "test" 프로필이 활성화 된 경우에는 미등록

@Profile에는 느낌표(!)를 사용해서 부정의 연산을 할 수도 있다.
위의 예제는 "test" 프로필이 비활성화 되었을 때만 Bean이 등록된다.

테스트 코드에서는 다음과 같이 작성했다.

@SpringBootTest
@ActiveProfiles("test")