[Spring] @Profile과 application.yml를 이용한 테스트환경 분리

du·2022년 7월 10일
0

Spring

목록 보기
3/6

회사 프로젝트가 로컬에서는 외부 연동이 되지 않아 통합 테스트 시마다 외부연동 부분 제거를 위해 소스 수정을 했었다.
이러한 불편함을 개선하기 위해 @Profile 어노테이션과 application.yml을 통해 각각의 환경에서 다른 Bean을 사용하도록 설정해보았다.

  • 예시는 사용법 정리를 위해 로직 없이 간략히 정리한 것으로 아래 환경에서 작성했다.
    spring boot 2.5
    gradle 7.2

예시

  1. build.gradle 수정하기
// Default Profile: local
ext.profile = (!project.hasProperty('profile') || !profile) ? 'local' : profile

sourceSets {
    main {
        resources {
            srcDirs "src/main/resources", "src/main/resources-${profile}"
        }
    }
}

tasks {
    processResources {
        duplicatesStrategy = org.gradle.api.file.DuplicatesStrategy.INCLUDE
    }
}
  1. apllication.yml를 생성 & 작성

# resources/apllication.yml
spring:
  profiles:
    active: local
  jpa:
      ...
      
# resources-dev/apllication.yml
spring:
  profiles:
    active: dev
  jpa:
      ...
  1. ProfileService의 구현체인 LocalProfileService, DevProfileService를 작성하고 @Profile 어노테이션을 이용하여 환경별로 실행될 Bean 결정
/** controller */
@RestController
public class ProfileController {

    private ProfileService profileService;

    public ProfileController(ProfileService profileService) {
        this.profileService = profileService;
    }

    @GetMapping("/api/test/profile")
    public void profileTest() {
        profileService.profile();
    }
}

/** service */
public interface ProfileService {
    void profile();
}


/** serviceImpl */
@Profile({"dev"})
@Slf4j
@Service
public class DevProfileService implements ProfileService  {
    @Override
    public void profile() {
        log.info("===================DevProfileService======================");
    }
}

/** serviceImpl */
@Profile({"local"})
@Slf4j
@Service
public class LocalProfileService implements ProfileService  {
    @Override
    public void profile() {
        log.info("===================LocalProfileService======================");
    }
}

결과

  • local(디폴트)로 실행
./gradlew clean bootRun

  • dev로 실행
./gradlew clean bootRun -Pprofile=dev

참고자료

0개의 댓글