Woopii Vyeolog

Maven과 Spring Legacy Project 설정파일 본문

Spring Framework

Maven과 Spring Legacy Project 설정파일

WooPii 2020. 3. 17. 14:03

pom.xml

메이븐(Maven)이란?

 

Maven은 자바 프로젝트의 빌드(Build)를 자동화 해주는 빌드 툴(Build Tool)이다.

 

빌드(Build) 란?

소스코드 파일을 컴퓨터에서 실행할 수 있는 독립 소프트웨어 가공물로 변환하는 과정 또는 그에 대한 결과물 이다.
이를 좀더 쉽게 풀어 말하자면 우리가 작성한 소스코드(java), 프로젝트에서 쓰인 각각의 파일 및 자원 등(.xml, .jpg, .jar, .properties)을 JVM이나 톰캣같은 WAS가 인식할 수 있는 구조로 패키징 하는 과정 및 결과물이라고 할 수 있다. 

빌트 둘(Build Tool)

빌드 툴이란 프로젝트 생성, 테스트 빌드, 배포 등의 작업을 위한 전용 프로그램.
계속해서 늘어나는 라이브러리 추가, 프로젝트 진행 중 라이브러리의 버전 동기화의 어려움 등을 해소하고자 등장.

 

Maven은 자바용 프로젝트 관리도구로 Apache Ant의 대안으로 만들어졌다. Maven은 Ant와 마찬가지로 프로젝트의 전체적인 라이프 사이클을 관리하는 도구 이며, 전반적인 프로젝트 관리 기능까지 포함이 되어 있다.(Build Tool + Project Management)

Maven은 많은 편리함과 이점이 있어 널리 사용되고 있다.

(프로젝트의 작성부터 컴파일, 페트스 등 프로젝트 라이프사이클에 포함되는 각 테스트를 지원해준다.)

Maven은 필요한 라이브러리를 특정 문서(pom.xml)에 정의해 놓으면 내가 사용할 라이브러리 뿐만 아니라 해당 라이브러리가 작동하는데에 필요한 다른 라이브러리들까지 관리하여 네트워크를 통해서 자동으로 다운받아 준다.
Maven은 중앙 저장소를 통한 자동 의존성 관리를 중앙 저장소(아파치재단에서 운영 관리)는 라이브러리를 공유하는 파일 서버라고 볼 수 있고, 메이븐은 자기 회사만의 중앙 저장소를 구축할수도 있다.
간단한 설정을 통한 배포 관리가 가능 하다.

 

 

Maven 설정파일


1) settings.xml
메이븐 빌드 툴과 관련한 설정파일

2) POM(프로젝트 객체 모델(Project Object Model))
POM은 pom.xml파일을 말하며 pom.xml은 메이븐을 이용하는 프로젝트의 root에 존재하는 xml 파일이다.
(하나의 자바 프로젝트에 빌드 툴을 maven으로 설정하면, 프로젝트 최상위 디렉토리에 "pom.xml"이라는 파일이 생성된다.)
Maven의 기능을 이용하기 위해서 POM이 사용된다. 
파일은 프로젝트마다 1개이며, pom.xml을 보면 프로젝트의 모든 설정, 의존성 등을 알 수 있다.

pom.xml의 예시

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
	
    <!--POM model의 버전-->
    <modelVersion>4.0.0</modelVersion>
	
    <!--프로젝트를 생성하는 조직의 고유 아이디를 결정한다. 일반적으로 도메인의 이름을 거꾸로 적는다.-->
    <groupId>kopo.exam</groupId>
    
	<!-- 프로젝트 빌드 시 파일의 대표이름이다. groupId내에서 유일해야 한다. 
    Maven을 이용하여 빌드 시 다음과 같은 파일이 생성된다. -->
    <artifactId>hello</artifactId>
    
    <!--프로젝트 이름-->
	<name>hello</name>
    
    <!--패키징 유형(jar, war, ear 등)-->
	<packaging>war</packaging>
    
    <!--프로젝트의 현재 버전, 프로젝트 개발 중일 때는 SNAPSHOT을 접미사로 사용-->
	<version>1.0.0-BUILD-SNAPSHOT</version>
    
    <!-- 버전관리시 용이 하다. ex) properties에서 자바 버전을 선언 하고 dependencies에서 
    다음과 같이 활용 가능 하다. <version>${java.version}</version>  -->
	<properties>
		<java-version>1.8</java-version>
		<org.springframework-version>5.0.7.RELEASE</org.springframework-version>
		<org.aspectj-version>1.6.10</org.aspectj-version>
		<org.slf4j-version>1.6.6</org.slf4j-version>
	</properties>
    
    <!--dependencies태그 안에는 프로젝트와 의존 관계에 있는 라이브러리들을 관리 한다.-->
	<dependencies>
		<!-- Spring -->
		<dependency>
		    <groupId>org.apache.maven.plugins</groupId>
		    <artifactId>maven-resources-plugin</artifactId>
		    <version>2.4.3</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework-version}</version>
			<exclusions>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				 </exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework-version}</version>
		</dependency>
				
		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>	
		
		<!-- Logging -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${org.slf4j-version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${org.slf4j-version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.15</version>
			<exclusions>
				<exclusion>
					<groupId>javax.mail</groupId>
					<artifactId>mail</artifactId>
				</exclusion>
				<exclusion>
					<groupId>javax.jms</groupId>
					<artifactId>jms</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jdmk</groupId>
					<artifactId>jmxtools</artifactId>
				</exclusion>
				<exclusion>
					<groupId>com.sun.jmx</groupId>
					<artifactId>jmxri</artifactId>
				</exclusion>
			</exclusions>
			<scope>runtime</scope>
		</dependency>

		<!-- @Inject -->
		<dependency>
			<groupId>javax.inject</groupId>
			<artifactId>javax.inject</artifactId>
			<version>1</version>
		</dependency>
				
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	
		<!-- Test -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.7</version>
			<scope>test</scope>
		</dependency>        
	</dependencies>
    
    <!--빌드에 사용할 플러그인 목록-->
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

 

▶ 엘리먼트
◎ modelVersion : POM model의 버전
◎ parent : 프로젝트의 계층 정보
◎ groupId : 프로젝트를 생성하는 조직의 고유 아이디를 결정한다. 일반적으로 도메인 이름을 거꾸로 적는다.
◎ artifactId : 프로젝트 빌드시 파일 대표이름 이다. groupId 내에서 유일해야 한다. Maven을 이용하여 빌드시 다음과 같은 규칙으로 파일이 생성 된다. artifactid-version.packaging의 규칙에 따라 생성된다.

위 예의 경우 빌드할 경우 Hello-1.0.0-BUILD-SNAPSHOT.war 파일이 생성된다.  
◎ version : 프로젝트의 현재 버전, 프로젝트 개발 중일 때는 SNAPSHOT을 접미사로 사용하고, 어디에 붙이냐에 따라 Maven에서 라이브러리를 관리하는 방식이 다르다고 한다.  
◎ packaging : 패키징 유형(jar, war, ear 등)
◎ name : 프로젝트, 프로젝트 이름
◎ description : 프로젝트에 대한 간략한 설명
◎ url : 프로젝트에 대한 참고 Reference 사이트
◎ properties : pom.xml에서 중복해서 사용되는 설정(상수) 값들을 지정해놓는 부분, 다른 위치에서 ${...}로 표기해서 사용할 수 있다. 버전관리시 용이 하다. 

ex) 하당 자바 버전을 선언 하고 dependencies에서 다음과 같이 활용 가능 하다.

( "<version>${java.version}</version>")  → 1.8이라고 쓴 것과 같다.
◎ dependencies : dependencies태그 안에는 프로젝트와 의존 관계에 있는 라이브러리들을 관리 한다.
◎ build : 빌드에 사용할 플러그인 목록

web.xml

 

web application 설정을 위한 설정파일이다. 배포 기술자로써 영어로는 DD(Deployment Descriptor) 이다.

이 파일은 WAS(Web Application Server)가 최초 구동될 때 즉 톰켓이 최초 구동될 때 web.xml을 읽고 그에 해당하는 설정을 구성한다. 즉 각종 설정을 위한 설정파일이라고 할 수 있다.

 

web.xml은 배포(deploy)할 때 Servlet의 정보를 설정한다. 

브라우저가 Servlet에 접근하기 위해서는 WAS(Web Application Server) 에 필요한 정보를 알려줘야 해당 Servlet을 호출 할 수 있다.

그 정보는, 1. 배포할 Servlet이 무엇인지. 2. 해당 Servlet이 어떤 URL에 매핑이 되는지 이다.

 

 

Spring MVC에서의 web.xml

 

web.xml에서 ContextLoaderListener (root-context) 와 DispatcherServlet(servlet-context) 생성하고 encodingFilter로 한글 처리하는 등의 설정을 할 수 있다.

 

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <!-- 여기에 등록된 설정 파일에 따라 등록된 Bean들은 모두 공유가 가능하다. -->
    <!-- root-context.xml을 정의 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring/root-context.xml</param-value>
	</context-param>
	
    <!-- ContextLoaderListener --> 
    <!-- 리스너로써 root-context.xml에 정의 되어있는 것들을 모든 서블릿과 필터가 공유할 수 있게 해준다고 함. -->
    <!-- Controller가 공유하는 Bean들을 포함하는 Spring Container를 생성한다 -->
    <!-- 공유하는 Bean: Dao, DataSource, Service --> 
    <!-- DispatcherServlet에 의해 생성된 Bean은 ContextLoaderListener에 의해 
    생성된 Bean을 참조할 수 있다.--> 
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

    <!-- Processes application requests -->
    <!-- DisparcherServlet -->
    <!-- 1. Spring Container를 생성한다. (Spring Container: Controller의 lifecycle 관리) -->
    <!-- 2. 클라이언트의 요청을 처음으로 받는 클래스 (Spring에서 제공) -->
    <!-- 3. 클라이언트의 요청을 Handler(Controller)에 보낸다. -->
	<servlet>
		<servlet-name>appServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- contextLoader가 해당 위치의 설정 파일을 읽어, 해당 파일을 dispatcher servlet으로 만든다. -->
        <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>
    
	<!-- /로 시작하는(/뒤에 공백) url 요청을 받아 appServlet에서 처리한다. -->
	<servlet-mapping>
		<servlet-name>appServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 한글처리 : 인코딩을 UTF-8로 설정하여 필터링하겠다는 설정이다. -->
    <filter> 
        <filter-name>encodingFilter</filter-name> 
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 
        <init-param> 
           <param-name>encoding</param-name> 
           <param-value>UTF-8</param-value> 
        </init-param> 
        <init-param> 
           <param-name>forceEncoding</param-name> 
           <param-value>true</param-value> 
        </init-param> 
     </filter> 
     <filter-mapping> 
        <filter-name>encodingFilter</filter-name> 
        <url-pattern>/*</url-pattern> 
     </filter-mapping>
     
</web-app>

 

Web Application Context

 

 

Root-context.xml

 

context란?

어떤 객체를 핸들링하기 위한 접근 수단
예 ) print를 하기 위해서는 print Context를 사용해야하고 Servlet을 수행하기 위해서는 Servlet Context를 사용해야함

 

전체 계층구조에서 최상단에 위치한 컨텍스트

서로 다른 서블릿 컨텍스트에서 공유해야하는 Bean들을 등록해놓고 사용할 수 있다.

이 context에 등록되는 모든 bean은 모든 context에서 사용 가능

웹 어플리케이션 전체에 적용해야하는 기능 ex)DB 연결, 로깅기능 등에 이용

Servlet Context에 등록된 Bean 이용 불가능!

Servlet Context와 동일한 Bean이 있을 경우 Servlet Context Bean이 우선된다.

하나의 컨텍스트에 정의된 AOP 설정은 다른 컨텍스트의 빈에는 영향을 미치지 않는다.

 

AOP(Aspect Oriented Programming)

AOP는 관점 지향 프로그래밍으로 "기능을 핵심 비즈니스 기능과 공통 기능으로 '구분'하고, 공통 기능을 개발자의 코드 밖에서 필요한 시점에 적용하는 프로그래밍 방법"이다. 

 

처음에 프로젝트 생성시에는 아무 내용도 없다. 이곳은 공통빈을 설정하는 곳으로 주로 View 지원을 제외한 비지니스 로직과 관련된  bean을 설정한다고 한다.  ( ex) Service / Repository(DAO) / DB/ log 등등 )

<?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">
	
	<!-- Root Context: defines shared resources visible to all other web components -->
		
</beans>

 

Servlet-context.xml

서블릿에서만 이용되는 컨텍스트
이 context에 등록되는 bean들은 servlet context에서만 사용 가능
타 서블릿과 공유하기 위한 Bean들은 루트 웹 어플리케이션 컨텍스트에 등록해놓고 사용해야 한다
DispatcherServlet은 자신만의 컨텍스트를 생성,초기화하고 동시에 루트 어플리케이션 컨텍스트를 찾아서 자신의 부모 컨텍스트로 사용

 

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		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">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	<!-- DispatcherServlet Context : 이 서블릿의 요청처리 인프라를 정의 -->
    <!-- 주로 View 지원 bean을 설정한다고 함 ex) Controller --> 
    
    
	<!-- Enables the Spring MVC @Controller programming model -->
    <!-- 어노테이션을 사용한다고 선언 --> 
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<!-- HTML 리소스 디렉토리 정의  -->
    <resources mapping="/resources/**" location="/resources/" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    	<!-- ViewResolver로 jsp와 name 을 매핑 -->
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>
	
    <!-- 베이스 패키지 하위 모든 어노테이션을 스캔해서 빈으로 등록하겠다는 것. -->
	<context:component-scan base-package="kopo.exam.hello" />
	
	
	
</beans:beans>

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


출처 & 참고

https://goddaehee.tistory.com/199

 

[Maven] Maven 이란? (정의, 예제)

[Maven] 메이븐 이란? (정의, 예제) 안녕하세요. 갓대희 입니다. 이번 포스팅은 [ 메이븐 알아보기 ] 입니다. : ) 1. 빌드 (Build) #1 빌드란? - 소스코드 파일을 컴퓨터에서 실행할 수 있는 독립 소프트웨어 가..

goddaehee.tistory.com

 

https://debugdaldal.tistory.com/127

 

[SPRING] web.xml , root-context.xml , servlet-context.xml 에 관하여...

1) web.xml 설정을 위한 설정파일이다. 배포 기술자로써 영어로는 DD(Deployment Descriptor) 이다. 이 파일은 WAS(Web Application Server)가 최초 구동될 때 즉 톰켓이 최초 구동될 때 web.xml을 읽고 그에 해당..

debugdaldal.tistory.com

https://gmlwjd9405.github.io/2018/10/29/web-application-structure.html

 

[Web] web.xml 설정 내용, 역할 및 간단한 예시 이해하기 - Heee's Development Blog

Step by step goes a long way.

gmlwjd9405.github.io

https://jaehun2841.github.io/2018/10/21/2018-10-21-spring-context/#%EB%93%A4%EC%96%B4%EA%B0%80%EB%A9%B0

 

Application-Context와 Servlet-Context | Carrey`s 기술블로그

들어가며 회사 업무 중에 AOP를 이용하여 개발 중에 AOP가 제대로 설정이 되지 않는 문제가 있었다. 문제의 원인은 Component-scan 위치에 따른 Bean 생성 위치에 있었다. core가 되는 프로젝트는 applicationContext에서 component-scan을 통해 bean을 생성 하고 있었고, 각 endpoint가 되는 프로젝트내의 패키지는 모두 servlet-context에서 component-scan을 하고 있었다. Bean의 생

jaehun2841.github.io

 

Comments