Profile이란?


Spring 3.1부터 포함된 기능으로 환경을 구분지어줄 때 사용한다. (여기서 환경은 일반적으로 DB 환경을 말함)

예) 개발 환경에 사용될 DB와 실제 환경에서 사용할 DB를 구분지어 주고 싶을 때. 

 

 

 

Profile 설정하기


Profile을 설정하기 위한 방법으로는 3가지가 있다.

 

1.JVM 프로퍼티로 등록

gradle.properties 파일에 jvm argument를 등록한다.

org.gradle.jvmargs=-Dspring.profiles.active=develop, production

 

또는 아래처럼 GUI로 설정할 수도 있는데, IntelliJ에서 [Run/Debug Configuration]에서 어떤 profile로 실행을 해주면될지를 설정한다.

 

 

2. 디폴트 프로퍼티 파일인 application.yml 파일에 spring.profiles.active 등록

별다른 프로파일 설정이 안 되어 있으면 디폴트인 application.yml을 읽을텐데, 여기서 원하는 프로파일을 활성화한다.

spring.profiles.active: develop

 

 

3. Java 코드로 프로파일 설정하기

Java 코드를 이용해서 원하는 프로파일을 활성화할 수도 있다.

@SpringBootApplication 클래스에서 애플리케이션 컨텍스트로 설정하는 방법인데, 아래 예시를 보자. 

@RequiredArgsConstuctor
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {

    final ConfigurableApplicationContext context;

    public static void main(String[] args) {
        setProfile("develop");
        SpringApplication.run(DemoApplication.class, args);
    }

    private void setProfile(String newProfile) {
        ConfigurableWebApplicationContext rootContext = (ConfigurableWebApplicationContext) context.getParent();
        rootContext.getEnvironment().setActiveProfiles(newProfile);
        rootContext.refresh();
        
        // Refreshing Spring-servlet WebApplicationContext
        context.getEnvironment().setActiveProfiles(newProfile);
        context.refresh();
    }
}

 

 

 

참고자료


[1] https://spring.io/blog/2011/02/14/spring-3-1-m1-introducing-profile

[2] https://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles

[3] https://docs.spring.io/spring/docs/3.2.8.RELEASE/javadoc-api//org/springframework/context/annotation/Profile.html

[4] https://www.lesstif.com/java/spring-profile-deploy-18220309.html