>  기사  >  Java  >  Maven을 통한 간편함: Java 프로젝트를 쉽게 구축하기

Maven을 통한 간편함: Java 프로젝트를 쉽게 구축하기

DDD
DDD원래의
2024-09-14 06:24:32506검색

Maven Made Simple: Building Java Projects with Ease

Maven을 사용한 빌드 자동화를 위한 따라하기 쉬운 가이드

Maven은 Java 개발자를 위한 필수 도구로서 프로젝트 빌드, 종속성 관리 및 버전 제어를 단순화합니다. Java를 처음 접하는 개발자이든 숙련된 개발자이든 Maven을 이해하면 작업 흐름이 크게 향상될 수 있습니다. 이 기사에서는 Maven의 작동 방식, 핵심 기능, 그리고 Maven이 복잡한 Java 프로젝트 관리를 위한 솔루션인 이유를 살펴보겠습니다. 반복적인 작업을 자동화하는 것부터 프로젝트를 체계적으로 유지하는 것까지 Maven은 개발을 더욱 원활하고 효율적으로 만듭니다. 마지막에는 더 빠르고 안정적인 빌드를 위해 Maven을 프로젝트에 통합하는 방법을 명확하게 이해하게 될 것입니다.

Maven은 종속성을 관리하는 것만이 아닙니다. 이는 또한 전체 개발 프로세스를 간소화하는 것이기도 합니다. 이는 "pom.xml" 파일을 사용하여 프로젝트의 종속성, 빌드 구성 및 플러그인을 정의하는 간단하면서도 강력한 구조를 따릅니다. 이 접근 방식을 사용하면 다양한 환경에서 프로젝트의 일관성을 유지하여 팀과 쉽게 협업할 수 있습니다. 또한 Maven의 라이프사이클 단계는 컴파일, 테스트, 패키징과 같은 작업을 자동화하므로 사용자는 코드 작성에 더 집중할 수 있습니다. Maven을 마스터하면 빌드 효율성이 향상될 뿐만 아니라 Java 애플리케이션의 전반적인 품질과 확장성이 향상됩니다. Maven의 장점을 좀 더 자세히 알아볼까요!

빌드 도구

빌드 도구는 애플리케이션 구축 프로세스를 자동화하는 데 필수적입니다. 수동으로 코드를 컴파일하고, 종속성을 다운로드하고, 테스트를 실행하고, 애플리케이션을 패키징하는 대신 빌드 도구가 이러한 작업을 자동으로 처리합니다. 개발을 간소화하고 일관성을 보장합니다.

빌드 도구가 일반적으로 수행하는 작업은 다음과 같습니다.

  • 소스코드를 실행 가능한 형태로 컴파일
  • Spring Boot, Hibernate, JUnit 등과 같은 필수 종속성을 다운로드
  • 단위 테스트를 실행하여 코드가 예상대로 작동하는지 확인하세요.
  • 애플리케이션을 JAR(독립 실행형 앱용) 또는 WAR(웹 앱용) 파일로 패키징합니다.

인기 있는 Java용 빌드 도구에는 다음이 포함됩니다.

  • 개미
  • 메이븐
  • 그레이들

"저는 Java 개발자로서 효율적인 프로젝트 관리, 빌드 자동화, 종속성 처리를 위해 Maven을 활용하여 개발 및 제공 프로세스를 간소화합니다."

메이븐

Maven은 애플리케이션 개발의 빌드 프로세스를 자동화하는 무료 오픈 소스 빌드 도구입니다. 이는 Apache Organization에서 제공합니다. Java 프로그래밍 언어를 사용하여 개발된 소프트웨어입니다. Maven의 도움으로 프로젝트 폴더 구조를 만들 수 있지만, 프로젝트를 개발할 때 프로젝트에 필요한 라이브러리와 프레임워크가 너무 많아서 수동으로 추가하기가 어렵습니다. Java 개발자에게는 시간이 많이 걸립니다. 해당 라이브러리와 프레임워크를 프로젝트 종속성이라고 하며 종속성은 예를 들어 Spring-Boot, Hibernate, Kafaka, 이메일 등입니다. 종속성을 다운로드하는 대신 maven S/W에 종속성을 다운로드하도록 지시할 수 있습니다. 또한 maven 소스 코드를 컴파일하고, API 기능 테스트를 위한 테스트 케이스를 실행하고, 애플리케이션을 jar(Java Archieve) / war(Web Archieve)로 패키징합니다.

Maven을 시작하려면 설치 프로세스에 공식 Maven 웹사이트에서 바이너리 패키지를 다운로드하고, MAVEN_HOME에 대한 환경 변수를 설정하고, 을 실행하여 터미널이나 명령 프롬프트를 통해 설치를 확인하는 작업이 포함됩니다. >mvn -버전.

Windows에 메이븐 설치

1단계: 시작하려면 Maven 다운로드

공식 홈페이지에서 Maven 다운로드: Maven 다운로드 페이지로 이동하세요. 최신 버전의 Maven용 바이너리 zip 아카이브를 다운로드하세요.

2단계: Maven 추출

다운로드 후: 다운로드한 ZIP 파일을 폴더에 추출합니다. 예를 들어 C:Program FilesApachemaven 또는 원하는 다른 위치를 사용할 수 있습니다.

3단계: 환경 변수 설정

명령줄에서 Maven을 사용할 수 있도록 하려면 환경 변수를 설정해야 합니다. 이 PC를 마우스 오른쪽 버튼으로 클릭하고 속성을 선택하세요

고급 시스템 설정 → 환경 변수를 클릭하세요.

시스템 변수에서 새로 만들기를 클릭하고 다음을 추가합니다.
변수 이름: MAVEN_HOME

변수값

C:\Program Files\Apache\maven

(또는 Maven을 추출한 디렉터리).
그런 다음 시스템 변수에서 경로 변수를 찾아 선택한 후 편집을 클릭하세요.

Add a new entry: %MAVEN_HOME%\bin.

4단계: 설치 확인

To check if Maven is installed correctly, open a command prompt and run the following command:

mvn -version

Maven Terminology

Archetype

An Archetype is a template that helps you quickly create a Maven project with a predefined structure. It defines the directory layout and initial configuration files to simplify project setup.

groupId

The groupId identifies the organization or project to which a Maven artifact belongs. It follows a reverse domain name convention (e.g., com.example.project) and ensures that dependencies are uniquely identifiable across the system.

artifactId

The artifactId is the name of the project or library. It's used along with the groupId and version to uniquely identify a specific project artifact, such as a JAR, WAR, or other packages.

packaging

The packaging type defines the build output type for your Maven project. Common options include jar, war, or pom. It determines how Maven will package the code, usually as a JAR or WAR file.

version

The version specifies the release or iteration of a Maven project. It's crucial for managing different versions of a library or artifact, allowing you to reference a specific version when adding dependencies to other projects.

SNAPSHOT : Under development
RELEASE : Development completed

Creating a Stand-Alone Application Using Maven With CMD

Maven is an excellent tool for building and managing Java projects, especially when it comes to creating stand-alone applications. Let’s walk through the steps of setting up a basic stand-alone Java application using Maven.

mvn archetype:generate -DgroupId=com.example.app -DartifactId=standalone-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

  • groupId: Uniquely identifies the project’s group.
  • artifactId: The name of your application.
  • archetypeArtifactId: Specifies the archetype for a simple Java project.

Once project created then verify project folder structure

standalone-app
│
├── src
│   ├── main
│   │   └── java               # Application source code (.java files)
│   │
│   ├── test
│   │   └── java               # Application Unit Test code (.java files)
│
└── pom.xml                    # Project Object Model (Maven configuration file)

src/main/java is containing the application source code.
src/test/java is containing the application test source code.
pom.xml file containing the maven configurations.

POM.XML

The pom.xml file, which stands for Project Object Model, is a crucial component of any Maven project. It is automatically generated when you create a Maven project and serves as the input file for Maven software. The pom.xml file defines the project’s metadata, including its name, version, and dependencies on various frameworks such as Spring, Hibernate, Kafka, and more. Instead of manually downloading these dependencies, you can specify them in the pom.xml file, and Maven will automatically fetch them for you. This makes managing project dependencies efficient and organized, allowing developers to focus on writing code without worrying about handling each library individually. Essentially, the pom.xml acts as a roadmap for Maven, guiding it on how to build and manage your Java project.

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.app</groupId>
    <artifactId>standalone-app</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>  <!-- Java version -->
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- JUnit for unit testing -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- Maven Compiler Plugin -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                </configuration>
            </plugin>

            <!-- Maven Shade Plugin for creating an executable JAR -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.4</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.example.app.App</mainClass>  <!-- Main class -->
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Maven Goals

Maven goals represent specific tasks that can be executed during the build lifecycle of a Maven project. Each goal corresponds to a distinct action, such as compiling code, running tests, packaging artifacts, or deploying to a repository.

By invoking these goals, developers can automate and streamline their build processes, ensuring that projects are built consistently and efficiently. Each goal can be run individually or as part of a larger lifecycle phase, providing flexibility in project management.

clean: Deletes the target directory, which contains compiled code and packaged artifacts, ensuring a fresh build.

compile: Compiles the source code of the project, producing class files from Java source files in the src/main/java directory.

test: Runs the unit tests defined in the src/test/java directory using a testing framework like JUnit.

package: Packages the compiled code into a distributable format, such as a JAR or WAR file, based on the project configuration in pom.xml.

install: Installs the packaged JAR/WAR file into the local Maven repository, making it available for other projects on the same machine.

deploy: Copies the packaged JAR/WAR file to a remote repository, making it available for other developers and projects.

site: Generates a site for the project, including documentation, reports, and project information, typically found in the target/site directory.

validate: Validates the project’s configuration and verifies that all required information is available before the build begins.

verify: Runs any checks to ensure the package is valid and meets quality standards, executing any verification tasks defined in the project.

archetype: Creates a new Maven project based on a specified archetype, setting up a project structure and initial files.

These goals can be executed from the command line, allowing developers to manage the build lifecycle effectively. You can run a specific goal using the following command format:

mvn [Goal]

Maven Repository

Maven repositories store project artifacts like libraries an dependencies. There are three main types of Maven repositories

Local Repository
Stores artifacts on your machine for quick access. it is a oyr system specific.

Remote Repository
Hosts artifacts on a server, accessible over the network. it is a organization specific.

Central Repository
Default public repository for widely used open-source libraries. it is accessed by everyone.

When you create a project and build it using Maven, it first checks your local repository (typically located at ~/.m2/repository) for any dependencies the project needs. If it finds the required dependencies in the local repository, Maven uses them directly, without downloading them again.

If the dependencies aren't available locally, Maven fetches them from a remote repository, such as Maven Central or another configured repository. Once downloaded, the dependencies are stored in the local repository for future use, so they don't need to be re-downloaded. This process helps optimize resource use and speeds up the build by preventing unnecessary downloads.

Maven build lifecycle

The Maven build lifecycle is a series of phases that automate the process of building and managing Java projects. It consists of three main lifecycles: default, clean, and site. The default lifecycle is the most commonly used, handling tasks like validating the project structure, compiling the code, running tests, packaging the output (e.g., into a JAR or WAR), and deploying the package to a remote repository. The clean lifecycle is responsible for cleaning up the project by deleting generated files from previous builds, while the site lifecycle is used to generate project documentation and reports. Each lifecycle consists of specific phases that are executed in sequence, ensuring that Maven handles everything from code compilation to deployment in a structured, automated way.

Conclusion

Maven has revolutionized how Java projects are built and managed, offering developers an efficient and automated approach to handling essential project tasks. Its core strength lies in dependency management, where Maven checks for required libraries in the local repository and fetches them from remote repositories like Maven Central if they're not available. This saves time and eliminates the need for manual dependency tracking, ensuring that projects always have the correct versions of required libraries.

The declarative nature of Maven, governed by the pom.xml file, standardizes the build process, making it easier to maintain consistency across different development environments. Whether it’s compiling code, running tests, or packaging the project for deployment, Maven's build lifecycle manages these steps seamlessly.

Additionally, Maven’s plugin system enhances its flexibility, enabling developers to integrate a wide array of tools and functionalities. Plugins for running tests, generating documentation, deploying artifacts, and more extend Maven’s utility far beyond a basic build tool.

By automating repetitive tasks and streamlining complex project setups, Maven allows developers to focus on writing code, improving productivity, and reducing potential errors. Its widespread adoption within the Java ecosystem makes it an indispensable tool for building modern, scalable, and maintainable Java applications.

위 내용은 Maven을 통한 간편함: Java 프로젝트를 쉽게 구축하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.