Java
[java] 자바 기반 설정 config
망고고래
2024. 6. 14. 12:05
자바 기반 설정 vs web.xml 설정
1. 자바 기반 설정
what?
@Configuration 애노테이션 사용, 자바 클래스를 스프링 설정 파일로 사용
why?
1)장점
- 타입 안정성: 컴파일시 타입 검사 가능 → 실수 감소
- 유연성: 자바 코드의 모든 기능 사용 가능 → 복잡한 로직을 포함한 설정 가능
- 가독성: 자동 완성, 리팩토링 등 가능
- 테스트 용이성: 설정 클래스 자체를 단위 테스트 가능
2. web.xml 설정
what?
서블릿 컨테이너에 의해 읽어지는 웹 애플리케이션의 배포 설명자. 스프링 설정을 포함해 애플리케이션의 다양한 설정을 정의할 수 있다.
why?
1)장점
- 표준화: 자바 EE 표준을 따름 → 다양한 애플리케이션 서버와 호환
- 명시적 구성 → 모든 설정이 xml 파일에 명시적으로 작성됨
2)단점
- 타입 안정성 부족: 문자열 기반 → 컴파일 시점에 타입 검사 불가
- 가독성 낮음 → 길어지기 쉽고 복잡한 설정을 표현하기 어려움
- 유연성 부족: 복잡한 로직 구현 어려움
- 테스트 어려움: xml 설정 자체를 단위 테스트 하기 어려움
how?
3. 자바 기반 설정 연습(maven 웹 프로젝트 기준)
1) pom.xml에 스프링 관련 의존성 추가
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>MySpringApp</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.3.20</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2)WebApplicationInitializer 구현
package com.example.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class MyWebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class, WebConfig.class);
DispatcherServlet dispatcherServlet = new DispatcherServlet(context);
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", dispatcherServlet);
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
3)스프링 설정 클래스 작성
(1)AppConfig.java: 애플리케이션의 일반적인 설정
package com.example.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
(2)WebConfig.java: 스프링 MVC 관련 설정
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
registry.viewResolver(resolver);
}
}
이후 컨트롤러, 뷰 페이지, 서비스 등 작성
서버를 설정하고 프로젝트를 실행하면 브라우저에서 접속할 때 스프링 MVC가 요청을 처리하고 JSP 페이지를 반환한다. WebAplicationInitializer는 애플리케이션 시작시 자동으로 실행되어 스프링 컨텍스트를 초기화한다.