개발

우리 팀을 위한 설정 정리

Domaya 2023. 1. 10. 17:01

스프링 레거시 프로젝트 설정 정리

 

pom.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"
   xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix">
         <value>/WEB-INF/views/</value>
      </property>
      <property name="suffix">
         <value>.jsp</value>
      </property>
   </bean>
   
   <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"></property>
    <property name="jdbcUrl"         value="jdbc:log4jdbc:oracle:thin:@localhost:1521:XE"></property>
    <property name="username"        value="springuser"></property>
    <property name="password"        value="1004"></property>
 </bean> 
 
    <bean id="driverManagerDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
      <constructor-arg ref="hikariConfig"></constructor-arg>
    </bean>
 
    <!-- MyBatis 설정 START  -->
    <bean id="sqlSessionFactoryBean"  class="org.mybatis.spring.SqlSessionFactoryBean">
       <property name="dataSource" ref="driverManagerDataSource"></property>
       <property name="mapperLocations" value="classpath*:kosa/mapper/*xml" />
   </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg index="0" ref="sqlSessionFactoryBean"/>
    </bean> 
    <!-- MyBatis 설정  END  -->

</beans>

root-context.xml

스프링이 로딩되면서 읽어 들이는 문서. 이미 만들어진 클래스들을 이용해 스프링의 빈으로 등록할 때 사용된다.

 

String으로 뷰 이름을 반환할 경우 이를 실제 뷰와 연결해주는 View Resolver

 

커넥션 풀인 HikariCP (DataSource를 통해 매번 데이터베이스와 연결하는 방식이 아닌, 미리 연결을 맺어주고 반환하는 구조)

 

SQL을 좀 더 빠르게 처리하도록 돕는 MyBatis

-자동적으로 Connection close() 가능. 내부적으로 PreparedStatement 처리. 리턴타입을 지정하는 경우 자동으로 객체 생성 및 ResultSet 처리

-가장 핵심적인 객체는 SQLSession과 SQLSessionFactory. 내부적으로 SQLSession을 만들어내고, 개발에서는 이를 통해 커넥션을 생성하거나 원하는 SQL을 전달, 결과를 리턴 받는 구조로 작성하게 된다.

-MyBatis는 내부적으로 preparedStatement를 이용해 SQL을 처리한다. 이때 전달되는 파라미터는 ?로 치환되어 처리되므로, 복잡한 SQL의 경우 이 값이 제대로 되었는지 확인하기 쉽지 않고 실행된 SQL의 내용을 정확히 확인하기 어렵다. SQL로그를 제대로 보기 위해서는 log4jdbc-log4j2라이브러리를 사용해야 한다.

log4j2

pom.xml에 라이브러리를 추가한 후에는 1) 로그 설정 파일을 추가하는 작업과 2)JDBC 연결 정보를 수정해야 한다.

log4jdbc.log4j2.properties추가

log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator

root-context.xml에는 jdbc드라이버 클래스를 net.sf.log4jdbc.sql.jdbcapi.DriverSpy로 해주면 된다. 그리고 JDBC 연결 URL 부분 중간에 log4jdbc문자열이 추가되는데 이는 위에 올려둔 코드대로 하면 됨.

로그의 기본 설정은 info 레벨이기 때문에 warn과 같이 좀 더 높은 레벨의 로그만 기록하게 수정하면 테스트 코드를 실행할 때 이전에 비해 로그의 양이 줄어드는 것을 확인할 수 있다.

https://mine-it-record.tistory.com/205

 

[SPRING] log4j2.xml 설정 (feat. level)

- 스프링 로그 log4j2.xml 설정하기 - log를 설정할 때 level 이 쓰여있는 것이 보이는데 이 역시 단계가 존재한다. 높은 등급에서 낮은 등급으로의 6개의 로그 레벨을 가지며 지정한 레벨 등급 이상의

mine-it-record.tistory.com

 

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

	<!-- Appenders -->
	<appender name="console" class="org.apache.log4j.ConsoleAppender">
		<param name="Target" value="System.out" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%-5p: %c - %m%n" />
		</layout>
	</appender>
	
	<!-- Application Loggers -->
	<logger name="kr.or.kosa">
		<level value="info" />
	</logger>
	
	<!-- 3rdparty Loggers -->
	<logger name="org.springframework.core">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.beans">
		<level value="info" />
	</logger>
	
	<logger name="org.springframework.context">
		<level value="info" />
	</logger>

	<logger name="org.springframework.web">
		<level value="info" />
	</logger>

	<!-- Root Logger -->
	<root>
		<priority value="warn" />
		<appender-ref ref="console" />
	</root>
	
</log4j:configuration>

나는 편의를 위해 여기의 info를 모두 warn으로 레벨을 올려줬다.

 

 

책에 따라 pom.xml에서

서블릿 버전과 maven plugin 버전도 바꿈

 

스프링 시큐리티를 쓰는 경우

	<!-- Spring Security -->

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>5.0.6.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-core -->
		<dependency>
		    <groupId>org.springframework.security</groupId>
		    <artifactId>spring-security-core</artifactId>
		    <version>5.0.6.RELEASE</version>
		</dependency>

교수님이 주신 코드에서는 4버전을 쓰는데 책에선 5버전이길래 바꿔둠

pom.xml에 위의 의존성을 추가한 후

security-context.xml을 만든다.

			 http://www.springframework.org/schema/security/spring-security.xsd

스프링 시큐리티 4.2버전까지는 괜찮지만 그 이상 버전부터는 security-context.xml의 상단부에서 .xsd앞에 있는 버전을 위와 같이 지워줘야 한다.

 

web.xml에

<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml
					/WEB-INF/spring/appServlet/security-context.xml
					</param-value>
		
	</context-param>
    
    <!-- 스프링 시큐리티 -->
      <filter>
	    <filter-name>springSecurityFilterChain</filter-name>
	    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	  </filter>
	  <filter-mapping>
	    <filter-name>springSecurityFilterChain</filter-name>
	    <url-pattern>/*</url-pattern>
	  </filter-mapping>
    
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

위와 같이 security-context.xml을 로딩하도록 설정,

필터를 이용해서 스프링에 동작하도록 설정한다.

 

security-context.xml에는 아래와 같이 설정을 추가한다.

<security:http>
	<security:form-login />
</security:http>

<security:authentication-manager>
</security:authentication-manager>

위 설정은, 스프링 시큐리티 동작을 위한 Authentication Manager와 스프링 시큐리티의 시작지점을 지정하는 작업이다.

 

이러고 구동해서 문제가 없으면 설정 성공~

 

 

 

------

각 xml은 뭘 의미하는걸까?

프로젝트 구동시 관여하는 XML은 web.xml, root-context.xml, servlet-context.xml 파일이다.

web.xml은 Tomcat 구동과 관련된 설정이고 나머지 두 파일은 스프링과 관련된 설정이다.

 

프로젝트의 구동은 web.xml에서 시작한다. web.xml의 상단에는 가장 먼저 구동되는 Context Listener가 등록되어있다.

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
	<!-- Creates the Spring Container shared by all Servlets and Filters -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

<context-param>에는 root-contxt.xml의 경로가 설정되어 있고, <listener>에는 스프링 MVC의 ContextLoaderListener가 등록되어있다. ContextLoaderListener는 해당 웹 애플리케이션 구동 시 같이 동작한다.

root-context.xml이 처리되면 파일에 있는 빈(Bean) 설정들이 동작하게 된다. root-context.xml에 정의된 객체(빈)들은 스프링의 영역(context)안에 생성되고 객체들 간의 의존성이 처리된다. root-context.xml이 처리된 후에는 스프링 MVC에서 사용하는 DIspatcherServlet이라는 서블릿과 관련된 설정이 동작한다.

	<!-- Processes application requests -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
		
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

org.springframework.web.servlet.DispatcherServlet 클래스는 스프링 MVC의 구조에서 가장 핵심적인 역할을 하는 클래스다. 내부적으로 웹 관련 처리의 준비작업을 진행하는데 이때 사용하는 파일이 servlet-context.xml이다. DispatcherServlet에서 XmlWebApplicationContext를 이용해서 servlet-context.xml을 로딩하고 해석하기 시작한다. 이 과정에서 등록된 객체(빈)들은 기존에 만들어진 객체(빈)들과 같이 연동된다.

 

Spring MVC는 내부적으로 Servlet/JSP를 처리하므로 개발자는 이러한 API에 신경쓰지 않고 웹 애플리케이션을 제작할 수 있다.