학습 정리(공식문서,강의)/JAVA,스프링

[Spring Boot] 스프링 부트로 프로젝트 시작 - 3. 환경설정

맨날개발 2024. 10. 16. 15:53

애플리케이션을 개발하다보면 다양한 환경에서 실행하게 된다. 예를 들어 개발환경, 배포환경 등이 있을 것이다. 이러한 환경마다 환경설정이 달라질 수 있다.

 

스프링 부트에서는 application.yml을 통해서 각기 다른 환경에 따른 환경설정을 간편하게 설정할 수 있도록 해준다.

이번에는 흔히 사용되는 환경설정을 정리해보았다. 여기에서 알아보는 내용은 내가 자주 사용한 것들만 모아놓았기 때문에 내용이 부족할 수 있다.

 

공통적으로 사용할 설정은 application.yml 에 정의하고 프로필마다 달리 설정하고 싶은 경우 개별 프로필별 환경설정에 정의한다.

 

 

자주 사용하는 환경 변수

프로필

spring
	profiles:
		active: dev
  • active : 활성화할 프로필 지정
    • 설정한 프로필에 따라 불러오는 환경설정이 결정됨
      • dev 프로필 사용시 application-dev.yml 자동 설정됨

 

서버 설정

server:
  port: 9000
  servlet:
    context-path: /context
  • port : 어플리케이션에서 사용할 포트 번호(localhost:port)
  • context-path : 어플리케이션에 접속 시 사용할 컨텍스트 경로(localhost:port/context-path)

 

데이터베이스

spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/testdb
    username: sa
    password:
  • driver-class-name : 사용할 DB의 JDBC 드라이버 클래스이름
  • url : DB에 연결하기 위한 URL 주소
  • username : DB 접속 유저 정보
  • password : DB 접속 유저 비밀번호

 

파일

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
  • max-file-size : 서버측으로 전송되는 개별 파일의 사이즈 제한
  • max-request-size : 서버측으로 전송 된 요청 전체의 사이즈 제한

 

로그

logging:
  config: classpath:logback-spring.xml
  level:
    root: debug
    
decorator:
  datasource:
    p6spy:
      enable-logging: false # p6spy enable
      multiline: true
      logging: sysout  # sysout, slf4j, file, custom
  • config : 환경설정에서 로깅 설정이 가능하지만 상세한 설정을 위해서 파일로 분리한다. 파일 경로 설정을 한다.
  • level : 패키지 또는 root 로 설정 가능. 패키지 별로 로그 레벨을 설정이 가능하다. root 로 설정 시 어플리케이션 전체에 적용.
    • trace, debug, info, warning, error
    • 개발 환경에서는 debug, 운영환경에서는 info 를 주로 설정
  • p6spy : JPA를 사용 시 호출되는 쿼리를 로깅할 수 있다. 이때 파라미터 값이 ? 가 아닌 실제 적용된 값으로 확인이 가능하다. 운영에서는 false 를 사용하자.
    • 해당 설정은 p6spy 의존성 추가 후 사용 가능

 

JPA

spring:
  jpa:
    properties:
      hibernate:
        default_batch_fetch_size: 1000
        jdbc:
          batch_size: 30
    hibernate:
      ddl-auto: update
      format_sql: false
      show_sql: true
      highlight_sql: true

  • default_batch_fetch_size : JPA는 지연로딩할 객체를 만났을 때, 해당 설정한 개수만큼 모일 때까지 기다렸다가 쿼리를 실행
  • batch_size : 한번에 insert/update 를 실행할 크기를 설정
  • ddl-auto : DDL 자동 생성 모드를 설정 가능(create, update, validate, create-drop, none)
  • show_sql : DB에 날리는 모든 쿼리를 확인 여부 설정
  • format_sql : 쿼리 포맷팅 여부 설정(설정하면 보기 좋게 바꿔준다)
  • highlight_sql : 쿼리 출력에 색을 부여

 

코드에 설정 적용하기

@Value 활용

@Value 어노테이션을 통해 환경변수를 가져올 수 있다.

아래에서 보듯이 필드, 메서드, 파라미터에서 모두 사용이 가능하다.

package org.springframework.beans.factory.annotation;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    String value();
}

 

사용방법은 아래와 같다.

public class Controller {
	
	// 필드에 설정
	@Value("spring.datasource.url")
	private String url;
	
	public void test(
			// 파라미터에 설정
			@Value("server.port") String port) {
  }
}

 

메서드에서 @Value를 사용할 때는 주로 setter에서 사용하게 된다.

@Component
public class Test {

    private String value;

    public String getValue() {
        return value;
    }

    @Value("${resource.path}")
    public void setValue(String value) {
        this.value = value;
    }
}

 

💡  @Value 어노테이션은 스프링 빈에서만 작동한다.

 

 

@ConfigurationProperties

@ConfigurationProperties 어노테이션을 사용해서 환경 설정을 자바 객체에 매핑이 가능하다. 하나의 객체에서 관리가 가능하고 타입 세이프한 장점을 가지고 있다.

@Getter
@AllArgsConstructor
@ConfigurationProperties("server")
public class KeyProperties {

    private long expirationTime;
}

 

💡 setter를 함께 사용하는 경우 어딘가에서 잘 못 수정하는 경우 전체에 영향을 줄 수 있다.

 


정리

spring
  profiles:
    active: dev
        
        
server:
  port: 9000
  servlet:
    context-path: /context
    
    
spring:
  datasource:
    driver-class-name: org.postgresql.Driver
    url: jdbc:postgresql://localhost:5432/testdb
    username: sa
    password:
    
    
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
      
      
logging:
  config: classpath:logback-spring.xml
  level:
    root: debug
    
    
decorator:
  datasource:
    p6spy:
      enable-logging: false # p6spy enable
      multiline: true
      logging: sysout  # sysout, slf4j, file, custom
      
      
spring:
  jpa:
    properties:
      hibernate:
        default_batch_fetch_size: 1000
        jdbc:
          batch_size: 30
    hibernate:
      ddl-auto: update
      format_sql: false
      show_sql: true
      highlight_sql: true