XML 설정 방식과 달리, 이 글에서는 Java 코드를 사용하여 Spring MVC 웹 프로젝트를 구축하는 방법을 설명합니다.
Spring MVC 개발 환경을 설정하는 핵심 단계는 세 가지입니다.
- Spring MVC 의존성 JAR 파일 추가
- DispatcherServlet 설정
- Spring MVC 구성
1. Spring MVC 환경 설정
Maven 기반 웹 프로젝트를 생성한 후, Spring 및 Spring MVC 의존성을 추가하여 JAR 파일을 포함시킵니다.
2. Spring MVC 구성 --- 2.1 Java를 사용한 DispatcherServlet 설정
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] {ApplicationConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {WebMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
설명: AbstractAnnotationConfigDispatcherServletInitializer를 확장하는 클래스는 자동으로 DispatcherServlet과 Spring 애플리케이션 컨텍스트를 구성합니다. Spring 애플리케이션 컨텍스트는 애플리케이션의 Servlet 컨텍스트 내에 위치합니다.
- getServletMappings() 메서드는 하나 이상의 경로를 DispatcherServlet에 매핑합니다.
- DispatcherServlet이 시작될 때, 애플리케이션 컨텍스트를 생성하고 구성 파일 또는 구성 클래스에 선언된 빈을 로드합니다. Spring 웹 애플리케이션에는 두 개의 애플리케이션 컨텍스트가 있습니다:
- DispatcherServlet이 생성한 애플리케이션 컨텍스트: 컨트롤러, 뷰 리졸버 및 프로세서 매핑과 같은 웹 구성 요소 빈을 로드합니다.
- ContextLoaderListener가 생성한 애플리케이션 컨텍스트: 애플리케이션의 백엔드 중간 계층 및 데이터 계층 구성 요소와 같은 다른 빈을 로드합니다.
getServletConfigClasses() 메서드가 반환하는 @Configuration이 적용된 클래스는 DispatcherServlet 애플리케이션 컨텍스트의 빈을 정의하는 데 사용됩니다. getRootConfigClasses() 메서드가 반환하는 @Configuration이 적용된 클래스는 ContextLoaderListener가 생성한 애플리케이션 컨텍스트의 빈을 구성하는 데 사용됩니다.
2. Spring MVC 구성 --- 2.2 Spring MVC 시작 패키지 스캔, 뷰 리졸러 및 정적 리소스 처리 구성
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
@ComponentScan("com.example")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.example")
public class ApplicationConfig {
}
주요 설정 항목:
- @ComponentScan: 컴포넌트 스캔을 활성화합니다. 반드시 기본 패키지를 지정해야 합니다.
- @EnableWebMvc: JavaConfig에서 Spring MVC를 활성화합니다.
- 뷰 리졸버 구성: JSP 파일을 찾을 때 뷰 이름에 특정 접두사와 접미사를 추가합니다.
- 정적 리소스 처리: DispatcherServlet이 정적 리소스 요청을 기본 Servlet으로 전달하도록 구성합니다.
3. 컨트롤러와 뷰 생성
4. 프로젝트 빌드 및 Tomcat 서버에 배포