[Spring] xml 설정 파일 예시
- web.xml (Deployment Descriptor): 웹 애플리케이션의 기본적인 설정. DispatcherServlet 등록, 필터 설정, 리스너 설정 등을 포함.
- Spring Application Context XML 파일: Spring 컨테이너의 설정. 빈(Bean) 정의, 의존성 주입(DI), AOP 설정 등을 포함. DispatcherServlet은 자신만의 Application Context를 가질 수 있음
1. web.xml (DispatcherServlet 등록)
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>My Spring MVC Application</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern> </servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
- <servlet>: DispatcherServlet을 정의.
- contextConfigLocation: DispatcherServlet이 사용할 Spring 설정 파일( servlet -context.xml)의 위치를 지정.
- load-on-startup: 웹 애플리케이션 시작 시 DispatcherServlet을 로드하고 초기화.
- <servlet-mapping>: DispatcherServlet을 URL 패턴에 매핑. (/는 모든 요청)
- <context-param> : Root Application Context (일반적으로 서비스, 리포지토리 등의 빈을 정의)를 설정.
- contextConfigLocation: Root Application Context 설정 파일(/WEB-INF/spring/root-context.xml) 위치
- <listener> : ContextLoaderListener를 등록하여 Root Application Context를 로드.
2. Spring Application Context XML 파일 ( servlet -context.xml )
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.example.controller"/>
<context:component-scan base-package="com.example.service"/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:resources mapping="/resources/**" location="/resources/" />
</beans>
- <context:component-scan>: 지정된 패키지(예: com.example.controller)에서 @Controller, @Service, @Repository, @Component 등의 어노테이션이 붙은 클래스들을 찾아 자동으로 빈으로 등록.
- <mvc:annotation-driven/>: @RequestMapping, @RequestBody, @ResponseBody 등과 같은 Spring MVC 어노테이션 기반 설정을 활성화.
- <bean class="...InternalResourceViewResolver">: ViewResolver를 설정. JSP를 뷰로 사용할 때, 뷰 이름에 접두사(/WEB-INF/views/)와 접미사(.jsp)를 붙여 실제 JSP 파일 경로를 찾는다.
- <mvc:resources> : 정적 리소스(CSS, JavaScript, 이미지 등)를 처리하기 위한 설정
. /resources/** URL 패턴으로 오는 요청을 /resources/ 디렉토리에서 찾는다. - <mvc:interceptors> : HandlerInterceptor를 설정.
파일 위치 (예시)
- src/main/webapp/WEB-INF/web.xml
- src/main/webapp/WEB-INF/spring/dispatcher-servlet.xml
- src/main/webapp/WEB-INF/spring/root-context.xml (선택 사항)
- src/main/webapp/WEB-INF/views/ (JSP 파일)
- src/main/webapp/resources/ (정적 리소스, 선택사항)
root-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example.service" />
<context:component-scan base-package="com.example.repository" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</bean>
</beans>
- root-context.xml에서는 주로 서비스, 리포지토리, 데이터베이스 연결 설정과 같이 웹 계층(Web Layer)이 아닌 빈들을 정의.
- component-scan으로 서비스와 리포지토리 클래스를 스캔.
- dataSource 빈은 데이터베이스 연결 설정을 정의하는 예시.
<mvc:interceptors> (인터셉터 설정)
컨트롤러의 실행 전/후에 특정 작업을 수행하고 싶을 때 인터셉터를 사용. 예를 들어 로깅, 인증/인가 체크, 요청/응답 데이터 조작 등에 활용할 수 있다.
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/> <mvc:exclude-mapping path="/login"/> <bean class="com.example.interceptor.MyInterceptor"/>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/admin/**"/>
<bean class="com.example.interceptor.AdminCheckInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
- <mvc:interceptor>: 인터셉터를 정의.
- <mvc:mapping path="...">: 인터셉터를 적용할 URL 패턴을 지정.
- <mvc:exclude-mapping path="...">: 인터셉터를 적용하지 않을 URL 패턴을 지정.
- <bean class="...">: 인터셉터 클래스 (HandlerInterceptor 인터페이스를 구현)를 지정.
- 여러 개의 인터셉터를 등록할 수 있다.
<mvc:view-controller> (간단한 뷰 매핑)
컨트롤러 로직 없이 URL과 뷰를 바로 매핑하고 싶을 때 사용.
<mvc:view-controller path="/about" view-name="about"/>
<mvc:view-controller path="/contact" view-name="contact"/>
- /about URL 요청이 오면 about 뷰 (예: /WEB-INF/views/about.jsp)를 반환.
- 컨트롤러 클래스를 작성할 필요가 없어 편리.
<mvc:default-servlet-handler/> (정적 리소스 처리)
Spring MVC의 DispatcherServlet이 모든 요청(/*)을 처리하도록 설정한 경우, 정적 리소스 (CSS, JavaScript, 이미지 등) 요청도 DispatcherServlet이 처리하려고 시도하기때문에 이를 방지하고 WAS(Web Application Server)의 default servlet에게 정적 리소스 처리를 위임하려면 이 설정을 사용.
<mvc:default-servlet-handler/>
- servlet-context.xml에 추가합니다.
- <mvc:resources>를 사용하는 경우에는 일반적으로 필요하지 않다. <mvc:resources>는 Spring MVC가 직접 정적 리소스를 처리하도록 하는 설정.
4. <context:property-placeholder> (프로퍼티 파일 사용)
데이터베이스 연결 정보, 외부 API 키 등과 같이 환경에 따라 달라지는 설정 값을 별도의 프로퍼티 파일(.properties)에 저장하고, XML 설정 파일에서 참조할 수 있다.
<context:property-placeholder location="classpath:database.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driverClassName}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>
- database.properties (src/main/resources 폴더에 위치):
db.driverClassName=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=your_password
- ${...} 표현식을 사용하여 프로퍼티 파일의 값을 참조.
5. <bean> 태그의 다양한 속성들 (의존성 주입)
- id: 빈의 고유한 식별자 (이름). 다른 빈에서 참조할 때 사용.
- class: 빈으로 생성할 클래스의 전체 경로.
- scope: 빈의 생성 범위.
- singleton (기본값): Spring 컨테이너 당 하나의 인스턴스만 생성.
- prototype: 빈을 요청할 때마다 새로운 인스턴스 생성.
- request: HTTP 요청마다 새로운 인스턴스 생성 (웹 애플리케이션에서만).
- session: HTTP 세션마다 새로운 인스턴스 생성 (웹 애플리케이션에서만).
- constructor-arg: 생성자 주입을 사용할 때 생성자 인자를 지정.
- property: setter 주입을 사용할 때 프로퍼티 값을 설정.
- init-method: 빈 초기화 시 호출할 메서드 지정.
- destroy-method: 빈 소멸 시 호출할 메서드 지정.
<bean id="myService" class="com.example.service.MyServiceImpl" scope="singleton">
<property name="repository" ref="myRepository"/>
<constructor-arg ref="anotherDependency"/>
<init-method>init</init-method>
<destroy-method>cleanup</destroy-method>
</bean>
<bean id="myRepository" class="com.example.repository.MyRepositoryImpl"/>
<bean id="anotherDependency" class="com.example.SomeOtherClass"/>
6. AOP 설정 (Aspect-Oriented Programming)
횡단 관심사(cross-cutting concerns)를 모듈화하기 위해 AOP를 사용할 수 있다. 로깅, 트랜잭션 관리, 보안 등에 활용.
<beans xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="...
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/> <bean id="loggingAspect" class="com.example.aspect.LoggingAspect"/>
<aop:config>
<aop:aspect ref="loggingAspect">
<aop:pointcut id="serviceMethods" expression="execution(* com.example.service.*.*(..))"/>
<aop:before pointcut-ref="serviceMethods" method="logBefore"/>
<aop:after-returning pointcut-ref="serviceMethods" method="logAfterReturning" returning="result"/>
<aop:after-throwing pointcut-ref="serviceMethods" method="logAfterThrowing" throwing="ex"/>
</aop:aspect>
</aop:config>
</beans>
- @AspectJ 어노테이션 방식 또는 XML 설정 방식을 사용할 수 있다. @AspectJ 방식이 더 간편.
7. 트랜잭션 관리 설정
<beans xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="...
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="dataSource" ...> ... </bean>
</beans>
- @Transactional 어노테이션을 사용하여 메서드 수준에서 트랜잭션을 관리할 수 있다.
- DataSourceTransactionManager는 JDBC 기반 트랜잭션 관리에 사용. JPA를 사용한다면 JpaTransactionManager를 사용.