본문 바로가기
Spring

[스프링부트 기초] 스프링부트 활용: 외부설정,프로파일,로깅

by 작심평생 2019. 12. 2.
[ 외부설정파일 ]
: application.property 또는 yml 등의 형태로 작성된 파일을 읽는다.
: 우선순위 존재. 자세한 내용은 "스프링 부트 개념과 활용 - 외부설정" 쪽 참고하자
: @Value 어노테이션 보다 바인딩에 융통성 있다. 프로퍼티 파일 내에서 카멜케이스나 케밥, 언드스코어로 작성해도 바인딩 되지만 @Value의 경우 오타나면  에러 발생. 좋은점은 SpEL 사용 가능한 것 밖에 없음..
: 참고 URL -> https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config

resource > application.property에 작성된 내용
- test.name = testName
- test.fullName = full_test
- test.sessionTimeOut = 23s // 뒤에 s, m, h 등 사용하면 VO쪽에 어노테이션 없이 사용 가능.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.seungsik.applicationcontext;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
 
import java.time.Duration;
 
@Component
@ConfigurationProperties("test"// 특정 property 참조
@Validated // 유효성
public class test {
    
    @NotEmpty
    private String name;
    
    private String fullName;
    
    private Duration sessionTimeout = Duration.ofSeconds(30); // 값이 없을 시 default 30초
 
    -- getter / setter 생략 --
}
cs

* resources 디렉토리 생성 후 property만든 경우 인텔리J 기준
  Project Structure > Modules > Mark as쪽에 버튼을 만든 resources 클릭 후 클릭하여 우측에 적용됐는지 확인

* 프로퍼티 내 메타정보를 통한 자동완성 이용하려면 dependency 추가 필요
1
2
3
4
5
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuation-processor</artifactId>
    <optional>true</optional>
</dependency>
cs





[ 프로파일 ]
: @Profile : 특정 상황에서 적용되게 하는 설정. @Configuration , @Component에 사용
: 프로퍼티에 spring.profiles.active = prod 이런 식으로 범위 지정
: 프로파일용 프로퍼티 만들 수 있다. --> application-{profile}.properties
: 프로파일 내에서 다른 프로파일 활성화도 가능 --> spring.profiles.include = test

ex) a.properties에 spring.profiles.active = test 면 profile이 test일때 적용되는데 a.properties안에 
spring.profiles.include = temp가 있으면 profile이 test일 때 temp.properties도 활성화 된다.

* 웹서버, 도커 등 배포 시 java -jar target/springinit-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod 처럼 Profile적용할 수 있고

* 개발 시에 인텔리J기준 Run/Debug Configurations > Configuation > Program arguments에 
   --spring.profiles.active=prod 줌으로 사용할 수도 있다. (--안되면 ㅡㅡ로 해보자..강의화면이 잘 안보임)





[ 로깅 ]
: program argument에 --debug 또는 VM option에 -Ddebug => 일부 핵심 라이브러리만 디버깅 모드로 찍어줌
: 전부 다 디버깅 모드 : --trace
: 컬러 출력 => spring.output.ansi.enabled = always 를 properties에 작성
: 파일 출력 => loggin.file 또는 logging.path
: 로그 레벨 조정 => logging.level.패키지 = 로그레벨

커스텀 로그 설정 파일 
: 프로퍼티나 옵션에 따로 작성하지 않음
    - Logback : logback-spring.xml 파일 생성 필요
    - Log4J2 : log4j2-spring.xml 파일 생성 필요

1
2
3
4
5
<?xml version="1.0" encoding="UTF-8"?
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="org.springframework.web" level="DEBUG"/> // name에는 패키지 이름
</configuration>
cs

log4j2로 바꾸려면 의존성 수정 필요 => 위에 링크에서 Configure Log4j for Logging 부분 확인


출처 : 인프런 - 백기선 스프링부트활용

댓글