0%

spring boot 에서 profile 사용한 application.properties 로딩 (gradle build)

환경(dev, qa, stage, prod) 에 따른 설정 로딩 요구

개발환경에 따라 설정값을 달리 로딩해야할 필요가 있습니다.

Eg) dev, qa, stage, prod

spring boot 에서는 이들을 profile 로 취급하며,
application-<profile>.properties 파일과 spring.profiles.active 값을 통해 이 문제를 해결할 수 있습니다.

여기에는 몇가지 규칙gradle build 에서 이를 사용하기 위한 설정이 있습니다.

application.properties 작성 규칙

application-<profile>.properties 파일명과 내용

먼저 원하는 profile 을 포함한 파일명을 작성해야합니다.

1
2
3
4
5
6
7
8
9
10
11
# prod 라는 profile 을 만든다고 하였을때
application-prod.properties

# qa
application-qa.properties

# etc
application-etc.properties

# custom
application-custom.properties

profile 에 들어갈 단어는 꼭 dev, local, qa 등과 같이 미리 정의된 keyword 가 아닙니다. 개발자 마음이긴 하나 통상 아래와 같은 약어를 많이 사용합니다.

profiles desc
dev 개발 환경
test 테스트 환경
prod 실서비서 환경

파일 내용에는 아래와 같이 현재 나의 profile 이 어떤것임을 명시해주어야 합니다.

application-prod.properties 파일의 경우

1
spring.profiles.active=prod

application-prod.yml 파일의 경우

1
2
3
spring:
profiles:
active: prod

application.properties (profile 이 없는 형태 = default)

아무런 profile 을 작성하지 않을경우 spring boot 는 default 라는 기본값을 사용합니다.
그렇다고 하여 application-default.properties 가 존재해야 하는것은 아닙니다.
profile 이 없다면 application.properties 를 가져오기때문입니다.

build.gradle 수정

gradle bootRun 시 스프링부트가 제공하는 spring.profiles.active 를 적용받기 위해 아래와 같은 설정을 추가해야 합니다.

1
2
3
4
bootRun {
String activeProfile = System.properties['spring.profiles.active']
systemProperty "spring.profiles.active", activeProfile
}

:warning: 주의 하실점은 이 설정을 최하단 적절한곳에 넣어주셔야 오류가 발생되지 않습니다.

build.gradle 샘플

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
plugins {
id 'org.springframework.boot' version '2.2.2.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
compileOnly {
extendsFrom annotationProcessor
}
}

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}

test {
useJUnitPlatform()
}

bootRun {
String activeProfile = System.properties['spring.profiles.active']
systemProperty "spring.profiles.active", activeProfile
}

Application 실행

intellij - spring boot Run/Debug

아래 사진과 같이 Active profiles 에 적용하고자 하는 환경값을 넣으면 (eg: prod)
application-prod.properties 의 설정을 읽어오게 됩니다.

gradle CLI

cli 에서 하신다면 아래와 같은 파라미터를 전달해주세요.

1
2
3
4
gradle bootRun -Dspring.profiles.active=prod
# -Dspring.profiles.active=prod
# -Dspring.profiles.active=dev
# -Dspring.profiles.active=stage

테스트

application.properties

1
2
server.port=8080
spring.redis.host=localhost

application-prod.properties

1
2
3
spring.profiles.active=prod # 이 값을 꼭 넣어주셔야 작동합니다.
server.port=8081
spring.redis.host=prodhost

:white_check_mark: application.yml, application-prod.yml 로도 동일하게 동작됩니다.

RedisConfig 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;

@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
System.out.println("spring.redis.host: " + host);
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(6379);
LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration);
return lettuceConnectionFactory;
}
..
..
// 생략
}

환경 주입 없이 테스트: default

1
2
3
4
5
6
7
8
9
10
11
2020-01-10 11:48:55.950  INFO 23460 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication on jwlee08PC with PID 23460 (C:\workspace\spring-boot-simple-api\build\classes\java\main started by ����� in C:\workspace\spring-boot-simple-api)
2020-01-10 11:48:55.954 INFO 23460 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
2020-01-10 11:48:56.520 INFO 23460 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-01-10 11:48:56.523 INFO 23460 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
2020-01-10 11:48:56.559 INFO 23460 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 17ms. Found 0 Redis repository interfaces.
2020-01-10 11:48:58.400 INFO 23460 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-01-10 11:48:58.413 INFO 23460 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-01-10 11:48:58.413 INFO 23460 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29]
2020-01-10 11:48:58.596 INFO 23460 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-01-10 11:48:58.596 INFO 23460 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2596 ms
spring.redis.host: localhost

환경 주입 테스트: prod

1
2
3
4
5
6
7
8
9
10
11
2020-01-10 11:52:20.750  INFO 3520 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication on jwlee08PC with PID 3520 (C:\workspace\spring-boot-simple-api\build\classes\java\main started by ����� in C:\workspace\spring-boot-simple-api)
2020-01-10 11:52:20.752 INFO 3520 --- [ main] com.example.demo.DemoApplication : The following profiles are active: prod
2020-01-10 11:52:21.685 INFO 3520 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-01-10 11:52:21.688 INFO 3520 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode.
2020-01-10 11:52:21.737 INFO 3520 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 19ms. Found 0 Redis repository interfaces.
2020-01-10 11:52:23.543 INFO 3520 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2020-01-10 11:52:23.555 INFO 3520 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-01-10 11:52:23.555 INFO 3520 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.29]
2020-01-10 11:52:23.756 INFO 3520 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-01-10 11:52:23.756 INFO 3520 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2938 ms
spring.redis.host: prodhost

느낀점

빌드 도구와 스프링부트의 인터페이스도 가끔 생각을 해야할것 같습니다.