본문 바로가기
SpringBoot/Common

Spring Profiles 설정 방법

by BAYABA 2021. 9. 13.
  1. 아래 출처를 참고하여 작성하였습니다.
  2. 개인 공부목적으로 작성한 글입니다.

1. Profile을 사용하는 이유

  1. Profile을 사용하면 Bean을 특정한 프로파일에만 매핑하여 Bean이 필요할 때만 주입받을 수 있습니다.
  • dev (development)
  • prod (production)
  • test

2. Profile 셋팅방법


2-1. @Profile

  1. @Profile 어노테이션을 사용하여 특정한 프로파일에만 사용할 Bean을 매핑할 수 있습니다. (어노테이션은 여러 프로파일을 가질 수 있습니다.)
//DevDatasourceConfig Bean은 dev 프로파일에서는 Bean이 활성화되지만, prod 환경에서는 활성화되지 않습니다.
@Component
@Profile("dev")
public class DevDatasourceConfig


// 아래와 같이 사용하면 dev Profile이 활성화되지 않았을 때만 DevDatasourceConfig Bean을 사용할 수 있습니다.
@Component
@Profile("!dev")
public class DevDatasourceConfig

2-2. XML에 표기하기

  1. Porfile은 XML 파일로도 구성할 수 있습니다.
  2. 태그에는 해당 프로필을 쉼표로 구분하여 사용하는 프로필을 정의할 수 있는 속성이 있습니다.
<beans profile="dev">
    <bean id="devDatasourceConfig" 
      class="org.baeldung.profiles.DevDatasourceConfig" />
</beans>

3. Profile 활성화 방법(Set Profiles)

  1. 다음 단계는 해당 Bean이 컨테이너에 등록되도록 프로파일을 활성화하고 설정하는 것입니다.

3-1. spring.profiles.active

  1. application.yml에서 spring.profiles.active 속성을 설정해주면 활성화되는 프로필을 지정할 수 있습니다.
spring:
  profiles:
    active: local

3-2. Maven Profile

  1. maven의 경우 아래와 같이 속성을 지정할 수 있습니다.
<profiles>
    <profile>
        <id>dev</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <spring.profiles.active>dev</spring.profiles.active>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <spring.profiles.active>prod</spring.profiles.active>
        </properties>
    </profile>
</profiles>

  1. 위에 설정한 값은 spring.profiles.active에서 @spring.profiles.active@ 위치를 대신합니다.
// .yml
spring:
  profiles:
    active: @spring.profiles.active@

// .properties
spring.profiles.active=@spring.profiles.active@

  1. pom.xml에서 리소스 필터링을 활성화합니다.
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
    ...
</build>

  1. 끝으로 패키징이나 빌드 시 적용할 Maven 프로필을 전환하기 위해 -P 매개변수를 추가합니다.
$ mvn clean package -Pprod
  • 이 명령은 prod 프로필용 애플리케이션을 패키징합니다.
  • 또한 실행 중일 때 이 애플리케이션에 대한 spring.profiles.active 값 prod를 적용합니다.

출처

  1. Spring Profiles

'SpringBoot > Common' 카테고리의 다른 글

Spring Multi profile 설정(YML)  (0) 2021.09.26
인터셉터(Interceptor)  (0) 2021.09.22
필터(Filter)  (0) 2021.09.22