스프링

[자바] 스프링의 환경 설정 : 프로파일(Profile) 사용하기

imcoding 2022. 7. 20. 17:51

현업에서는 환경을 다양하게 해서 특정 환경에서만 특정 Bean이 동작하도록 설정해주는 환경 설정이 있다.

@Component
public class PaymentType implements PaymentService {

}
@Component
public class PaymentAmount implements PaymentService {

}

위와 같이 동일한 인터페이스로 만들어진 두 클래스가 있고 Bean으로 지정되어 있다.

이 상태로 PaymentService 인터페이스를 실행시키려 하면 아래와 같은 메시지가 나타날 것이다.

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.zerobase.convpay.service.DiscountInterface' available: expected single matching bean but found 2: discountByConvenience,discountByPayMethod

두 클래스 중 어느것을 우선적으로 사용할 것인지 정하지 않아서 나타나는 에러 메시지이다.

물론, Bean 구현체가 여러개일 경우 @Primary나 @Qualifier 등을 통해서 우선순위에 따라 주입할 수 있다.

하지만 오늘은 제목에서도 나와있듯이 환경 설정을 통해 해당 문제를 해결해 보겠다.

 

 

 

Profile
&
환경변수 설정

 

 

환경 설정은 해당 Bean에 @Profile 을 추가해서 사용할 수 있다.

@Profile은 총 세가지가 있다.

"test"(테스트환경)       /       "beta"(운영환경 전단계)       /      "production"(운영환경)
@Component
@Profile("test")
public class PaymentType implements PaymentService {

}
@Component
@Profile("production")
public class PaymentAmount implements PaymentService {

}

위 코드처럼 Profile을 지정해주면 된다.

Profile 어느 환경에서 해당 Bean을 주입시킬 지 결정해준다고 보면 된다.

참고로, 환경변수 앞에 느낌표를 붙이면 그 환경만 제외하고 실행되는 것이다. ex) @Profile("!production")

 

 

 

그리고 사용 중인 IDE에서 프로젝트의 환경변수를 바꿔주면 끝이다.

환경변수는 아래와 같은 형식으로 작성된다.

spring.profiles.active=test
spring.profiles.active=beta
spring.profiles.active=production

 

이렇게 Profile을 지정하고 환경변수 설정을 끝내면 환경에 맞는 Bean이 실행될 것이다.