SPRING

스프링 프로파일 (Profile)

JUMP개발자 2020. 4. 14. 00:37

프로파일

- 빈들의 그룹

- Environment의 역할은 활성화할 프로파일 확인 및 설정

 

프로파일 USECASE

- 테스트 환경에서는 A라는 빈을 사용하고, 운영서버에서는 B라는 빈을 사용하고 싶다.

 

프로파일 정의하기

- 클래스에 정의

@Configuration @Profile("test")

@Conponent @Profile("test")

 

- 메소드에 정의

@Bean @Profile("test")

 

 

아래와 같이 @Repository 어노테이션을 붙이지 않으면 ComponentScan에서 스캔을 통해 Bean 객체 등록이 되지 않는다.

1
2
3
4
5
6
7
8
9
10
11
12
 
import org.springframework.stereotype.Repository;
 
//@Repository
//@profile("test")
// 위와같은 식으로 많이씀.
// @profile("!production") -> prodcution이 아닌 경우에만 실행.
public class TestBookRepository implements BookRepository {
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

아래와 같이 Configuration을 등록하고 test 프로파일일 때만 아래 클래스가 실행되게 설정한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
 
@Configuration
@Profile("test"// Test Profile 일때만 사용하는  설정파일
public class TestConfiguration {
 
    @Bean
    public BookRepository bookRepository() {
        return new TestBookRepository();
    }
    
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

프로파일 설정을 안하면 아래와같이 Bean  객체 생성이 안되기 때문에 아래와 에러 발생

 

아래와 같이 Profile을 설정하면 Test Profile을 인식하여 에러가 발생하지 않는다.