티스토리 뷰


2016/09/08 - [개발/JAVA] - 스프링 부트(Spring boot)에서 프로퍼티 사용하기

이전 글에 이어서...

이번에는 프로파일별로 프로퍼티를 설정 해 볼 예정입니다.

개발을 하다보면 로컬->개발기->상용기 형식으로 바뀌면서 설정값들이 바뀌어야 하는 경우가 많습니다.

개발할때는 로그를 1초마다 찍고 싶고 개발기에서는 5초마다 찍고 싶을때 주석을 풀고 지우고 하지 말고 아래처럼 프로파일로 관리를 하면 됩니다.

yaml형식의 파일을 사용하며 하나의 파일 안에서 프로파일 별로 설정값들이 설정됩니다.


application.properties

더 이상 사용하지 않습니다.  지워주세요.


application.yml

이제 모든 설정은 이 yml파일 안에서 하게 됩니다.

yml파일은 탭문자가 들어가면 안되며, 아래와 같이 구분은 ---으로 하게 됩니다.


첫번째 섹션은 현재 어떤 프로파일로 동작을 할건지를 선언해주고 있습니다.

(application.properties 파일의 spring.profiles.active=local과 동일합니다)

또한 프로파일에 구분없이 사용할 값들도 정의되어있습니다.


그 다음 local 프로파일이 적용 되었을 경우 사용할 설정값과 

dev 프로파일이 적용되었을 경우 사용할 설정 값이 ---로 구분되어서 선언되어 있습니다.


spring:

  profiles: 

    active: local

  timerName: exampleTimer


---

spring:

  profiles: local

  task:

    fixedDelay: 1000

    name: localTask


---

spring:

  profiles: dev

  task:

    fixedDelay: 5000

    name: devTask


Timer.java

프로파일과 상관없이 돌아가는 timeName속성을 찍는 로그를 추가해 줍니다.

package net.donnert.spring.boot;

import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
public class Timer {
	Logger logger = LoggerFactory.getLogger(this.getClass());
	private AtomicInteger loopCounter = new AtomicInteger();
	
	@Autowired
	private StopWatch watch;
	
	@Value("${spring.task.name}")
	private String taskNamePrefix;
	
	@Value("${spring.timerName}")
	private String timerName;
	
	@PostConstruct
	public void init() {
		logger.info("{} init", timerName);
		watch.start();
	}

	@Scheduled(fixedDelayString = "${spring.task.fixedDelay}")
	public void tick() throws InterruptedException{
		watch.stop();
		logger.info(watch.prettyPrint());
		String taskName = taskNamePrefix + "-" + String.valueOf(loopCounter.getAndIncrement());
		watch.start(taskName);
	}

	@Bean
	public StopWatch watch() {
		return new StopWatch();
	}
}


실행(local)

현재 설정되어 있는 상태로 수행을 합니다.

아래처럼 공통 설정인 timerName는 exampleTimer로 찍히면서 

프로파일별 설정을 따라 localTask가 1초 마다 찍히고 있습니다.


  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v1.4.0.RELEASE)


2016-09-12 13:28:03.434  INFO 6600 --- [           main] net.donnert.spring.boot.Application      : Starting Application on ezen-PC with PID 6600 (D:\Java\workspace\Ezens\paynow_simulator\spring.boot\target\classes started by donne in D:\Java\workspace\Ezens\paynow_simulator\spring.boot)

2016-09-12 13:28:03.437  INFO 6600 --- [           main] net.donnert.spring.boot.Application      : The following profiles are active: local

2016-09-12 13:28:03.498  INFO 6600 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@49d8c528: startup date [Mon Sep 12 13:28:03 KST 2016]; root of context hierarchy

2016-09-12 13:28:04.442  INFO 6600 --- [           main] net.donnert.spring.boot.Timer            : exampleTimer init

.....

...

2016-09-12 13:28:08.617  INFO 6600 --- [pool-1-thread-1] net.donnert.spring.boot.Timer            : StopWatch '': running time (millis) = 4170

-----------------------------------------

ms     %     Task name

-----------------------------------------

00166  004%  

01002  024%  localTask-0

01000  024%  localTask-1

01002  024%  localTask-2

01000  024%  localTask-3



실행(dev)

application.yml의 3번째 라인의 active: local을 active: dev로 바꿔줍니다.

아래처럼 공통 설정인 timerName는 exampleTimer로 찍히면서 

프로파일별 설정을 따라 devTask가 5초 마다 찍히고 있습니다.

  .   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::        (v1.4.0.RELEASE)


2016-09-12 13:30:32.465  INFO 10976 --- [           main] net.donnert.spring.boot.Application      : Starting Application on ezen-PC with PID 10976 (D:\Java\workspace\Ezens\paynow_simulator\spring.boot\target\classes started by donne in D:\Java\workspace\Ezens\paynow_simulator\spring.boot)

2016-09-12 13:30:32.468  INFO 10976 --- [           main] net.donnert.spring.boot.Application      : The following profiles are active: dev

2016-09-12 13:30:32.521  INFO 10976 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@65efb4be: startup date [Mon Sep 12 13:30:32 KST 2016]; root of context hierarchy

2016-09-12 13:30:33.379  INFO 10976 --- [           main] net.donnert.spring.boot.Timer            : exampleTimer init

.....

...

2016-09-12 13:30:48.542  INFO 10976 --- [pool-1-thread-1] net.donnert.spring.boot.Timer            : StopWatch '': running time (millis) = 15158

-----------------------------------------

ms     %     Task name

-----------------------------------------

00154  001%  

05001  033%  devTask-0

05001  033%  devTask-1

05002  033%  devTask-2


마치며

스프링에서 프로파일은 콤마로 구분하여 여러개를 해도 됩니다.

자바에서 context.getEnvironment().getActiveProfiles()를 하면 현재 설정된 프로파일들을 가져올 수 있습니다.

이를 응용하여 확장이 용이한 프로그램 개발이 가능해집니다.


2016/09/19 - [개발/JAVA] - 스프링 부트(Spring boot)에서 logback 적용하기


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함