새소식

반응형
WEB/Spring

Spring boot profile 설정 방법 [properties 기준]

  • -
반응형

2024-02-27


사진: Unsplash 의 Thimo van Leeuwen


1. 준비

 

우선 자신의 개발 환경에 맞게 properties를 생성해 준다.

 

 

네이밍은 위와 같이 application-[개발환경].properties의 형식으로 만들어주어야 한다.

 

현재 프로파일이 어떤 건지 확인할 수 있게 아래와 같이 application-[개발환경].properties에 명시에 주었다.

 

profile.now=dev_profile

2. 방법

 

아래는 application-[개발환경].properties 에 명시에 둔 키값을 맵핑할 enum이다.

 

public enum ProfileKey {
    NAME;
    public String str() {
        return "profile.now";
    }
}

다음으로 현재 프로파일 정보를 편하게 사용하기 위한 enum을 하나 생성해 준다. (해당 부분은 옵션으로 하드코딩으로 구현해도 된다.)

 

public enum ProfileCode {
    LOCAL_PROFILE,
    DEV_PROFILE,
    MAIN_PROFILE;


    public String lowerStr() {
        return this.name().toLowerCase();
    }

    public String upperStr() {
        return this.name().toLowerCase();
    }
}

이후 ProfileConfig를 생성하여 현재의 프로파일 정보를 확인 할 수 있게끔 Config 를 만들어준다. 

 

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Slf4j
@Configuration
public class ProfileConfig {

    public final Environment env; //설정값을 가져오기 위한 객체


    public ProfileConfig(Environment env) {
        this.env = env;
    }

    @PostConstruct
    public void init(){
        //로그 찍기
        log.info(" ===== [INIT] nowProfile = {}", env.getProperty(ProfileKey.NAME.str()));
    }

    //현재 프로파일 정보를 가져온다.
    public ProfileCode now(){

        String nowProfile = env.getProperty(ProfileKey.NAME.str());
        if(nowProfile == null) return ProfileCode.DEV_PROFILE;
        else if(nowProfile.equals(ProfileCode.LOCAL_PROFILE.lowerStr())) return  ProfileCode.LOCAL_PROFILE;
        else if(nowProfile.equals(ProfileCode.DEV_PROFILE.lowerStr())) return  ProfileCode.DEV_PROFILE;
        else if(nowProfile.equals(ProfileCode.MAIN_PROFILE.lowerStr())) return  ProfileCode.MAIN_PROFILE;
        else return  ProfileCode.DEV_PROFILE;
    }
}

해당 config의 init을 통해 프로젝트 실행 시 아래와 같이 현재 profile 정보를 확인할 수 있고 now() 함수를 통해 어떤 클래스에서 든지 현재의 프로파일 정보를 확인 할 수 있게 된다.

 


3. 설정방법

 

인텔리제이에서는 run/debug configurations에서 profile을 설정할 수 있고

 


배포 시에는 생성되는 -jar 파일에 아래와 같은 옵션을 주어 생성하면 명시된 프로파일 정보에 따라 프로젝트가 빌드된다.

 

-Dspring.profiles.active=dev

메인 이미지 출처 : 사진: UnsplashThimo van Leeuwen  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.