티스토리 뷰

APACHE/MAVEN

Maven 메이븐구조 및 설치

Giles Blog 2019. 5. 27. 17:02
728x90

1. 메이븐

  java 진영에서 프로젝트 빌드와 의존성 라이브러리를 관리하는 도구이다.

 참조 및 다운로드 :  http://maven.apache.org/

 

 Maven의 특징은

   1.  빌드 프로세스를 쉽게 만듬

   2. 동일한 빌드 시스템 제공

   3. 프로젝트 정보제공

 

Maven 구조

 

Maven과 Gradle 차이점

    1) 메이븐은 xml방식이며, 그래들은 groovy 스크립트 언어를 사용하고 동적인 빌드가 가능하다.

      ( 안드로이드는 기본이 Gradle로 되어있음. 메이븐도 사용가능하다고함)

   2) Maven은 멀티프로젝트에서 상속구조이나 Gradle은 주입방식이다. 멀티프로젝트에서는 Gradle이 더 적합하다.

 

 

2. 플러그인

  

  •     메이븐은 플로그인을 구동해주는 프레임워크(plugin execution framework)이다. 모든 작업은 플러그인에서            수행한다.
  •     플러그인은 다른 산물출(artifacts)와 같이 저장소에서 관리된다.
  •     메이븐은 여러 플러그인으로 구성되어있으며, 각각의 플러그인은 하나 이상의 goal(명령,작업)을 포함하고 있다.      Goal은 Maven의 실행단위이다.

   

  • 플러그인과 골의 조합으로 실행한다
mvn <plugin>:<goal> = mvn archetype:generate
  • 메이븐은 여러 goal을 묶어서 lifecycle phases로 만들고 실행한다.
mvn <phase> = mvn install

 

 1) 플러그인 목록

구분 Plugin명 설명
core plugins clean, compiler, deploy, failsafe, install, resources, site, surefire, verifier 기본 단계에 해당하는 핵심 플러그인
Packaging types/tools ear, ejb, jar, rar, war, app-client, shade 압축 도구
Reporting plugins changelog, changes, checkstyle, javadoc, pmd, surefire-report 리포팅 도구
Tools ant, antrun, archetype, assembly, dependency, pdf, plugin, repository  기타 다양한 도구

 

3. 라이프 사이클

메이븐은 프로젝트 생성에 필요한 단계(phases)들을 Build Lifecycle 이라 정의하고 default, clean, site 세가지로 

표준 정의한다. Lifecycle은 Build Phase들로 구성되며 이련의 순서를 갖는다. phase는 실행단위로서 

goal과 바인딩 된다. 아래 사진은 Build default 라이프 사이클의 주요 pahse이고 그 밑은 전체이다.

 

  • clean : 빌드 시 생성되었던 산출물을 삭제
    1. pre-clean : clean 작업 전에 사전작업
    2. clean : 이전 빌드에서 생성된 모든 파일 삭제
    3. post-clean : 사후작업
  • default : 프로젝트 배포절차, 패키지 타입별로 다르게 정의됌
    1. validate : 프로젝트 상태 점검, 빌드에 필요한 정보 존재유무 체크
    2. initialize : 빌드 상태를 초기화, 속성 설정, 작업 디렉터리 생성
    3. generate-sources : 컴파일에 필요한 소스 생성
    4. process-sources : 소스코드를 처리
    5. generate-resources : 패키지에 포함될 자원 생성
    6. compile : 프로젝트의 소스코드를 컴파일
    7. process-classes : 컴파일 후 후처리
    8. generate-test-source : 테스트를 위한 소스 코드를 생성
    9. process-test-source : 테스트 소스코드를 처리
    10. generate-test-resources : 테스팅을 위한 자원 생성
    11. process-test-resources : 테스트 대상 디렉터리에 자원을 복사하고 가공
    12. test-compile : 테스트 코드를 컴파일
    13. process-test-classes : 컴파일 후 후처리
    14. test : 단위 테스트 프레임워크를 이용해 테스트 수행
    15. prepare-package : 패키지 생성 전 사전작업
    16. package : 개발자가 선택한 war, jar 등의 패키징 수행
    17. pre-integration-test : 통합테스팅 전 사전작업
    18. integration-test : 통합테스트
    19. post-integration : 통합테스팅 후 사후작업
    20. verify : 패키지가 품질 기준에 적합한지 검사
    21. install : 패키지를 로컬 저장소에 설치
    22. deploy : 패키지를 원격 저장소에 배포
  • site : 프로젝트 문서화 절차
    1. pre-site : 사전작업
    2. site : 사이트문서 생성
    3. post-site : 사후작업 및 배포 전 사전작업
    4. site-deploy : 생성된 문서를 웹 서버에 배포

4. 의존성

개발자는 프로젝트에 사용할 라이브러리를 pom.xml에 dependency로 정의만 해두면 메이븐이 repository에서 검색해서

자동으로 추가해준다. 심지어 참조하고 있는 library까지 모두 찾아서 추가해준다. ( 의존성 전이 )

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.8.2</version>
 <scope>test</scope>
</dependency>

   1) 의존관계 제한 기능

      불필요한 라이브러리 다운로드를 방지하기 위해 추가기능을 제공한다.        

  • Dependency mediation : 버전이 다른 두 개의 라이브러리가 동시에 의존 관계에 있을 경우 Maven은 좀더 가까운 의존관계에 있는 하나의 버전만을 선택
  • Dependency management : 직접 참조하지는 않으면서 하위 모듈이 특정 모듈을 참조할 경우, 특정 모듈의 버전을 지정
  • Dependency scope : 현재 Build 단계에 꼭 필요한 모듈만 참조할 수 있도록 참조 범위를 지정
    • compile : 기본값, 모든 classpath에 추가, 컴파일 및 배포 때 같이 제공
    • provided : 실행 시 외부에서 제공, 예를들면 WAS에서 제공되어 지므로 컴파일 시에는 필요하지만, 배포시에는 빠지는 라이브러리들
    • runtime : 컴파일 시 참조되지 않고 실행때 참조
    • test : 테스트 때만
    • system : 저장소에서 관리하지 않고 직접 관리하는 jar 파일을 지정 
    • import : 다른 pom파일 설정을 가져옴, <dependencyManagemet>에서만 사용
  • Excluded dependencies : 임의의 모듈에서 참조하는 특정 하위 모듈을 명시적으로 제외처리
  • Optional dependencies : 임의의 모듈에서 Optional로 참조된 모듈은 상위 모듈이 참조될 때 Optional 모듈은 참조제외
<dependency> 
    <groupId>junit</groupId> 
    <artifactId>junit</artifactId> 
    <version>4.8.2</version> 
    <scope>system</scope> 
    <url>c:\폴더 or webapp\폴더</url>
</dependency>

2. 의존 라이브러리의 경로

  • 로컬 : USER_HOME/.m2/repository 에 저장된다.
  • setting.xml 파일로 저장됩니다.

  setting.xml 기본파일

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">
      <localRepository>${user.home}/.m2/repository</localRepository>
    </settings>

 

그외 setting은 다음을 참조할것  http://maven.apache.org/settings.html

 

5. Profile

Maven은 서로 다른환경에서 따라 달라지는 설정을 각각 관리할수있는 Profile기능을 제공한다.

local, dev, real 환경에 따라 설정들을 미리 정해놓고 컴파일 타임에서 선택하려고 사용할수있다.

  

  Spring profile

@Configuration
public class AppConfig {

	@Profile("dev")
	@Bean
	public CacheManager cacheManager() {	//...	}

	@Profile("live")
	@Bean
	public EhCacheManagerFactoryBean ehCacheCacheManager(){  	//...	}

	@Profile("testdb")
	@Bean
	public DataSource dataSource() {	//...	}
}

@Profile을 통해 적용되는 코드를 나누고, web.xml에서 다음과 같은 설정을 통해 profile을 설정합니다.

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>live</param-value>
</context-param>

<context-param>
    <param-name>spring.profiles.active</param-name>
    <param-value>dev, testdb</param-value>
</context-param>

  Maven profile

 maven을 통한 profile 관리는 compile시점에서 mvn -P[profileName] clean package 명령어를 통해

 어떤 자원을 사용할지 결정한다.

  • profile 설정파일들이 들어갈 폴더구조를 만든다.
  • profile 해당하는 resource 폴더 구조를 적어둔다.

 pom.xml

<project>

	<profiles>
		<profile>
			<id>local</id>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
			<properties>
				<environment>local</environment>
			</properties>
		</profile>
		<profile>
			<id>real</id>
			<properties>
				<environment>real</environment>
			</properties>
		</profile>	        
		<profile>
			<id>dev</id>
			<properties>
				<environment>dev</environment>
			</properties>
		</profile>
	</profiles>
    
    <build>
		<resources>
			<resource>
				<directory>src/main/resources/${environment}</directory>
			</resource>
		</resources> 
	</build>

</project>

   참조 . https://dreambringer.tistory.com/15 Maven property의 필요성 및 profile 세팅(여러환경 대상)

 

 

6. POM.xml

   pom.xml 은 메이븐을 이용하는 프로젝트의 root에 존재하는 xml파일이며, pom은 프로젝트 객체모델

   (Project Object Model)을 뜻한다. 프로젝트 당 1개가 있다. 이것만 보면 프로젝트 설정 및 의존 라이브러리를 

   확인할수있다.

 

  엘리먼트

  • <groupId> : 프로젝트의 패키지 명칭

  • <artifactId> : artifact 이름, groupId 내에서 유일해야 한다.

<groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId>
  • <version> : artifact 의 현재버전 ex. 1.0-SNAPSHOT

  • <name> : 어플리케이션 명칭

  • <packaging> : 패키징 유형(jar, war 등)

  • <distributionManagement> : artifact가 배포될 저장소 정보와 설정

  • <parent> : 프로젝트의 계층 정보

  • <dependencyManagement> : 의존성 처리에 대한 기본 설정 영역

  • <dependencies> : 의존성 정의 영역

  • <repositories> : 이거 안쓰면 공식 maven 저장소를 활용하지만, 사용하면 거기 저장소를 사용

  • <build> : 빌드에 사용할 플러그인 목록을 나열

  • <reporting> : 리포팅에 사용할 플러그인 목록을 나열

  • <properties> : 보기좋게 관리가능, 보통 버전에 많이 쓴다.

<!-- properties 에 이렇게 추가하면 --> 
<spring-version>4.3.3.RELEASE</spring-version> 

<!-- dependencies 에 이렇게 쓸수 있다. --> 
<version>${spring-version}</version>

 

Maven 구조

<modelVersion>4.0.0</modelVersion> 

    <!-- The Basics --> 
     <groupId>...</groupId> 
     <artifactId>...</artifactId>
     <version>...</version>
     <packaging>...</packaging> 
     <dependencies>...</dependencies> 
     <parent>...</parent> 
     <dependencyManagement>...</dependencyManagement> 
     <modules>...</modules>
     <properties>...</properties> 
     
     <!-- Build Settings --> 
     <build>...</build> 
     <reporting>...</reporting> 
     
     <!-- More Project Information --> 
     <name>...</name> 
     <description>...</description>
     <url>...</url> 
     <inceptionYear>...</inceptionYear> 
     <licenses>...</licenses>
     <organization>...</organization> 
     <developers>...</developers> 
     <contributors>...</contributors>
     
     <!-- Environment Settings -->
     <issueManagement>...</issueManagement> 
     <ciManagement>...</ciManagement> 
     <mailingLists>...</mailingLists> 
     <scm>...</scm> 
     <prerequisites>...</prerequisites> 
     <repositories>...</repositories> 
     <pluginRepositories>...</pluginRepositories> 
     <distributionManagement>...</distributionManagement> 
     <profiles>...</profiles>



'APACHE > MAVEN' 카테고리의 다른 글

내부망,폐쇄망 Maven Repository 설정 및 사용하기  (0) 2019.06.19
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함