Spring Boot 3 웹 개발 핵심 기능 정리

1. 자동 구성 및 웹 애플리케이션 설정

Spring Boot 3는 spring-boot-starter-web 의존성을 통해 웹 애플리케이션을 간편하게 구성할 수 있도록 제공합니다.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

기본적으로 @EnableAutoConfiguration 어노테이션은 AutoConfigurationImportSelector를 사용하여 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 파일에 정의된 모든 자동 구성 클래스를 로드합니다.

주요 자동 구성 클래스 목록

  • WebMvcAutoConfiguration – Spring MVC 기본 설정
  • ServletWebServerFactoryAutoConfiguration – 서블릿 기반 웹 서버 설정
  • DispatcherServletAutoConfiguration – 디스패처 서블릿 구성
  • HttpEncodingAutoConfiguration – HTTP 인코딩 설정
  • MultipartAutoConfiguration – 파일 업로드 관련 설정
  • ErrorMvcAutoConfiguration – 오류 처리 설정
  • RestTemplateAutoConfiguration – REST 클라이언트 설정

구성 파일 기반 설정 항목

  • Spring MVC 설정: 정적 리소스 경로, 요청 매핑 등
  • 공통 웹 설정 (spring.web): 정적 리소스 위치, 캐시 정책, 인코딩 방식
  • 파일 업로드 설정 (spring.servlet.multipart)
  • 서버 설정 (server): 포트, 인코딩, 컨텍스트 경로 등

2. 기본 웹 기능 및 구성 요소

기본적으로 다음 기능이 활성화됩니다:

  • 정적 리소스 처리: src/main/resources/static, public, resources, META-INF/resources 폴더 내 파일은 직접 접근 가능
  • 뷰 리졸버 자동 등록: ContentNegotiatingViewResolver, BeanNameViewResolver
  • 데이터 변환기 자동 등록: Converter, Formatter, GenericConverter
  • HTTP 메시지 컨버터 지원: JSON, XML 등 다양한 형식 출력 가능
  • 국제화 및 오류 메시지 처리: MessageCodesResolver 포함
  • index.html 자동 인식 및 제공
  • 데이터 바인딩 및 유효성 검사: ConfigurableWebBindingInitializer 사용

커스텀 설정 방법 비교

방법특징
1. @Configuration + WebMvcConfigurer (비 @EnableWebMvc)기본 설정 유지 + 커스텀 추가 가능
2. WebMvcRegistrations 빈 등록핵심 컴포넌트(예: RequestMappingHandlerMapping) 교체 가능
3. @EnableWebMvc + WebMvcConfigurer전체 제어권 획득, 기본 설정 무효화

결론: 기본 동작을 유지하면서 일부 설정을 변경하고 싶다면, @Configuration 클래스에서 WebMvcConfigurer를 구현하되 @EnableWebMvc는 생략하세요.

3. 정적 리소스 처리 규칙

정적 리소스는 다음 순서로 탐색됩니다:

  1. classpath:/META-INF/resources/
  2. classpath:/resources/
  3. classpath:/static/
  4. classpath:/public/

또한, 다음과 같은 규칙이 적용됩니다:

  • webjars 경로: /webjars/** 요청 시 classpath:/META-INF/resources/webjars/에서 찾음
  • 캐싱 설정:
    • spring.web.resources.cache.period: 캐시 주기 (초 단위)
    • spring.web.resources.cache.cachecontrol: HTTP 캐시 제어 헤더 설정
    • spring.web.resources.cache.use-last-modified: 최종 수정 시간 사용 여부

4. WebMvcAutoConfiguration 작동 원리

자동 구성이 활성화되기 위한 조건:

  • 웹 애플리케이션 유형 (서블릿 기반)
  • 필수 클래스 존재: Servlet, DispatcherServlet, WebMvcConfigurer
  • 컨테이너에 WebMvcConfigurationSupport가 없음
  • 다른 자동 구성 이후 실행됨

등록되는 필터

  • HiddenHttpMethodFilter: HTML 폼에서 _method 파라미터를 통해 PUT, DELETE 요청 전달
  • FormContentFilter: POST 요청 본문의 폼 데이터를 파싱해 application/x-www-form-urlencoded 처리

5. 다중 클라이언트 대응 (내용 협상)

클라이언트 요청에 따라 적절한 응답 형식을 반환하는 기능입니다.

1. Accept 헤더 기반 협상

클라이언트가 Accept: application/json 또는 text/xml 등을 포함하면, 서버는 해당 형식으로 응답합니다.

  • 실제 처리는 HttpMessageConverter가 담당합니다.
  • 기본 제공 컨버터들:
    • StringHttpMessageConverter
    • ByteArrayHttpMessageConverter
    • ResourceHttpMessageConverter
    • MappingJackson2HttpMessageConverter (JSON)
    • MappingJackson2XmlHttpMessageConverter (XML)

YAML 지원 추가

YAML 형식을 지원하려면 다음을 수행해야 합니다:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
</dependency>

설정 파일에 추가:

spring.mvc.contentnegotiation.media-types.yaml=text/yaml

2. 요청 파라미터 기반 협상

URL에 ?type=json 또는 ?type=xml 형태로 요청하면, 해당 형식으로 응답됩니다.

활성화 방법:

spring.mvc.contentnegotiation.favor-parameter=true
spring.mvc.contentnegotiation.parameter-name=type

이렇게 하면 http://localhost:9000/person?type=json 요청 시 JSON, type=xml 시 XML 형식으로 응답받을 수 있습니다.

왜 기본으로 JSON을 반환하는가?

기본 스타터 spring-boot-starter-web에는 spring-boot-starter-json이 포함되어 있으며, 이는 jackson-databind를 포함합니다. 따라서 객체 → JSON 직렬화가 자연스럽게 지원됩니다.

태그: Spring Boot 3 Web Development auto-configuration WebMvcConfigurer HttpMessageConverter

6월 8일 00:00에 게시됨