Code

Apache Maven in Java: What it is, how to install, configure, and work with repositories / ITech content

Apache Maven in Java: What it is, how to install, configure, and work with repositories / ITech content

Course with employment: “Profession Java developer”

Learn More

Java developers often cite Apache Maven as their best assistant. This framework is designed to automate project builds using the description of their structure in POM (Project Object Model) files. Maven significantly simplifies the process of dependency management, building, and deploying applications, making it an indispensable tool in the developer's arsenal. Thanks to its flexibility and wide capabilities, Apache Maven ensures reliability and efficiency in Java software development.

In this article, we will take an in-depth look at the basics of working with the project builder and delve into its key component - the pom.xml file. We will discuss its structure, main elements, and their purpose so that you can effectively use this tool in your projects.

What you will learn about Maven: Maven is a powerful tool for managing Java projects. It simplifies the process of building, managing dependencies, and automating testing. As you work with Maven, you'll become familiar with its architecture, configuration basics, POM file usage, and repository management principles. You'll also learn how to effectively use plugins to extend functionality and automate various development tasks. Maven helps organize your project structure and ensures highly reproducible builds. Mastering Maven will significantly simplify your development process and increase your team's productivity.

  • Why is it needed and are there any similar tools?
  • How to install it correctly on your computer and is it possible to do without it?
  • How to configure it and build your first project?
  • Why does it need repositories and what types there are?

What is Maven?

Maven is a powerful tool for automatically building projects in Java and other programming languages. It simplifies the development process by allowing developers to efficiently integrate necessary libraries and frameworks, manage their versions, and organize the project structure. Furthermore, Maven provides the ability to create and maintain documentation, which contributes to improved code quality and simplifies its maintenance. Using Maven in projects ensures standardization and automation of builds, making it an indispensable tool in the arsenal of a modern developer.

Creating an application for managing databases in Java requires the Spring and Hibernate frameworks, as well as the JUnit library for unit testing and the database itself. Although it is possible to assemble all the components manually, this can lead to complications due to numerous dependencies. In this case, Maven comes to the rescue. This tool automates the process of adding the necessary dependencies to the project and simplifies assembling the application into an executable file. Using Maven reduces the likelihood of errors and saves time, making it an essential element in the development of Java applications.

Maven is one of the most popular tools for building projects, but it is not the only one. Developers also use alternatives such as Gradle and Ant. However, Maven is rightfully considered the gold standard in the software development industry. Its widespread adoption and community support make it the preferred choice for many projects.

Installing Maven

Maven can be installed either manually or using integrated development environments (IDEs) that already include this build tool. The second option is more convenient and quicker, but in this article we will focus on the traditional method of installing Maven directly on the operating system.

To work effectively with Java, you need to install and properly configure the JDK on your computer. We have already provided instructions on how to properly install the JDK, which will help you start developing in Java without any difficulties.

Download the Apache Maven build tool archive corresponding to your operating system from the official website. It is recommended to create a separate folder for unpacking, as you will need this path later.

If you are using a Linux operating system, you can run the installation through the terminal. This will allow you to effectively manage the installation process and quickly execute the necessary commands. Make sure you have the necessary access rights to perform the installation.

To work effectively with Maven and run it from the command line or terminal, you need to set up environment variables. The process of setting up environment variables varies depending on the operating system. Properly setting up environment variables helps ensure the correct functioning of Maven, which greatly simplifies the process of managing projects and dependencies.

Windows is an operating system developed by Microsoft, which is widely used on personal computers and laptops. It offers a user-friendly interface, a high degree of compatibility with various software, and many built-in features. Windows supports a variety of applications, from office suites to graphic editors, making it a universal tool for work and entertainment.

Since its inception, Windows has gone through many updates and versions, each of which has improved performance, security, and functionality. Today, Windows 10 and Windows 11 remain the most popular versions, providing users with modern technologies, such as touchscreen support and integration with cloud services.

In addition, Windows offers a vast ecosystem of programs for various needs, allowing users to find solutions for any task. The operating system is also actively developed, which ensures that it is up-to-date and meets modern security and performance requirements.

Using Windows allows users to easily connect to other devices, providing compatibility with a variety of peripherals. This makes it an ideal choice for both home and business use.

Setting environment variables on Windows 7, 10, and 11 is carried out using the same procedure. To do this, right-click on the This PC icon and select Properties from the context menu. After that, follow the path: "Advanced system settings", then go to the "Advanced" section and select "Environment Variables".

In the "Environment Variables" window, find the "Path" variable and click the "Edit" button. This will allow you to edit the values ​​​​stored in the variable, which is necessary for the proper operation of various applications and tools. Make sure the added paths are correct to avoid possible errors when running programs.

A window listing all environment variables. Although they are usually sorted alphabetically, you may need to scroll through the list of them. Screenshot: Skillbox Media

In the window that appears, click the «Create» button and enter the full path to the bin folder located in the unpacked Maven archive. Make sure the path is specified correctly to ensure that Maven works properly.

Screenshot: Skillbox Media

Check the environment variables settings for Maven. Open a command prompt and enter the command mvn -v. If Maven is installed correctly, you'll see its version information. This will help you confirm that the toolkit is configured correctly and ready to use.

Screenshot: Skillbox Media

Linux and Mac are popular operating systems that offer users a variety of features and tools. Linux, being an open-source platform, offers flexibility and customization, making it an ideal choice for developers and system administrators. On the other hand, the Mac, created by Apple, offers an intuitive interface and a high degree of integration with other Apple products, making it a preferred choice for designers and creative professionals. Both operating systems support a wide range of software and applications, allowing users to effectively complete their tasks. Linux offers a variety of distributions, such as Ubuntu, Fedora, and CentOS, each with its own features and designed for different user needs. Mac, in turn, provides access to exclusive applications such as Final Cut Pro and Logic Pro, which are highly regarded in the industry. When choosing between Linux and Mac, it is important to consider your needs and preferences. Linux may suit those who value freedom and customization, while Mac can be a great choice for those looking for a stable and user-friendly system with support for professional software.

Open a text editor and navigate to the ~/.bashrc or ~/.bash_profile file on Linux, or .zshrc on macOS. This file is located in your user's home directory. If the file is missing, create it and add the following lines:

Specify the path to your terminal configuration file: for Linux, this may be ~/.bashrc or ~/.bash_profile, and for macOS, .zshrc. Proper configuration of these files is necessary for Maven to work correctly.

Check the environment variables settings for Maven. To do this, open a terminal and run the mvn -v command. If everything is configured correctly, you will see a message with the current Maven version. Make sure your environment variables are set correctly to avoid issues when working with projects.

Screenshot: Skillbox Media

The last line for Mac users will indicate family: «mac». This allows the system to correctly recognize and apply fonts appropriate for the given operating system. Support for various platforms, including Mac, ensures the correct display of content and improves the user experience. Don't forget to check the font settings for maximum compatibility with different devices.

For working with Maven, IntelliJ IDEA is the optimal choice. This development environment provides all the necessary tools for effectively working with Maven-based projects, as the project builder is integrated into the IDE out of the box. IntelliJ IDEA facilitates the configuration and management of dependencies, which makes development more productive and convenient.

Maven settings in the integrated development environment (IDE) are available on the right side of the workspace after creating a Java project. To access these settings, open the Maven panel, where you can manage dependencies, build configuration, and plugins. This will allow you to effectively configure the project and optimize it for development. Make sure you regularly check and update your Maven settings to keep dependencies up-to-date and use the latest versions of plugins. Properly configuring Maven in your IDE will help simplify the process of building and managing your project.

Screenshot: Skillbox Media

Read also:

To convert a regular IDEA project to a Maven project, you need to follow a few steps. First, open your project in IntelliJ IDEA. Then, go to the «File» menu and select «Project Structure». In the window that opens, select «Modules» and add a new module, selecting the "Maven" type.

After that, you will need to configure the pom.xml file. This file is the main one for Maven and contains information about the project, its dependencies and plugins. You can add the necessary dependencies, specifying their versions and the repositories from which they will be downloaded.

It is also important to set the correct settings for compilation and testing. Make sure that your project uses the appropriate versions of Java and other libraries that may be required.

Don't forget to update the project structure after making changes to pom.xml so that IntelliJ IDEA can download all dependencies.

By following these steps, you can easily convert your regular IDEA project to a Maven project, which will greatly simplify dependency management and application building.

Configuring Maven and Building the Project

Let's start by creating a project template. Using a development environment will significantly reduce time, as it will automatically generate the necessary parameters for our project. This will greatly simplify the setup process and speed up its launch.

Creating a new project is an important step that requires careful planning and preparation. First, define the goal of your project and the target audience. This will help you better understand what exactly you want to achieve and how your proposal will be received.

After that, create a clear plan, including key milestones and deadlines. Pay attention to the required resources and budget to avoid unexpected expenses along the way.

It's also worth considering the choice of tools and technologies that will help you implement the project. Don't forget the importance of feedback: regular interaction with the team and stakeholders will allow you to make adjustments early and increase the chances of a successful completion.

Remember that creating a new project is not just a task, but an opportunity to implement your ideas and bring something new to your field of activity.

Screenshot: Skillbox Media

The program will prompt you to select Maven Archetype as a project build template. Select this option and in the presets window that opens, select Archetype quickstart. After that, click the Create button to create the project.

Screenshot: Skillbox Media

In the project window, you can watch how Maven accesses the repositories and begins downloading the necessary dependencies. This process is standard and expected when setting up a project.

Screenshot: Skillbox Media

The left side of the screen shows the project structure. An important element is the App.java class, which includes the main method. To find it, navigate to the src folder, then open the main and java sections. The App.java file contains a small snippet of code that performs the main function of the application.

The method works like this: it prints the message "Hello World!" to the console. This simple example is often used to demonstrate the basic principles of programming and working with console output. This approach allows beginners to quickly become familiar with the language syntax and understand how to perform basic operations. Using the "Hello World!" method is a tradition in programming education and helps establish the first connection between the code and the result of its execution.

Now open the pom.xml file. This file is the key configuration element of your project, containing information about its structure, dependencies, and settings. It is arguably the main driving force behind Maven, providing project management and build automation. Properly configuring pom.xml allows you to effectively manage libraries and plugins, significantly simplifying the process of developing and deploying applications.

When you open the file, you will find the following code:

Let's look at the main aspects of this topic.

The project is the main element that includes all the necessary information about the project.

The xmlns, xmlns:xsi, and xsi:schemaLocation attributes in the pom.xml file are used to define the namespace and schema. These attributes specify which elements should be present in the file and how they should be structured. Correct use of these attributes ensures correct recognition and processing of data in the project, which is critical to ensuring compatibility and functionality in the development environment.

modelVersion is the version of the POM model used in this file. In our case, version 4.0.0 is used. This information is important for the correct management of dependencies and project settings in build systems such as Maven. Version 4.0.0 includes updates and improvements that provide better compatibility and functionality.

groupId, artifactId, and version are key elements for uniquely identifying project contents. These parameters play an important role in dependency management systems such as Maven. Correct use of these identifiers allows for efficient management of libraries and resources, and ensures compatibility between different project components. Make sure that the values ​​of these elements are set correctly to avoid conflicts and dependency issues.

  • groupId is the team identifier. In our case, it is org.example, the same as the package with the App class. In large companies, the identifier identifies a group or team of developers. For example, imagine what the identifier of the company ACME might look like. Web developers in this company would use the group identifier com.acme.webapps, and mobile developers would use com.acme.mobile.
  • artifactId is the identifier of the artifact. Maven uses applications, packages, and files as artifacts. Like the group ID, it is needed to avoid confusion in the project. By default, the artifact ID corresponds to the project name we specified when creating it. In our case, it is maven-example.
  • version — the project version. It changes when the project is updated.

Project packaging is an important step that determines the type of packaging used. In our case, we use a JAR file to package all project components. JAR files (Java Archive) allow you to conveniently organize and distribute Java applications, providing convenient access to classes, metadata, and resources. Choosing the JAR format ensures that the project can be easily deployed and integrated into various environments, which increases its compatibility and usability.

The project name is an important element that plays a key role in its identification and promotion. A well-chosen name helps create a unique image and attract the target audience. It should be memorable, easy to pronounce, and reflect the essence of the project. When choosing a name, consider its online visibility, including domain names and social media profiles. A unique and SEO-optimized name will help improve your project's visibility in search engines, which in turn will lead to increased traffic and user interest. Therefore, choose your project name carefully to ensure it successfully distinguishes you from the competition.

A URL is a web address used to access a specific project-related resource on the internet. It serves as a unique identifier, allowing users to find and interact with the content posted on the website. A proper URL structure can improve your project's visibility in search engines and enhance its SEO optimization. Consider the importance of using keywords in the URL to make the address more understandable and attractive to users and search engines.

In the properties section, we define variables for the project. In this case, we specify the encoding, setting it to UTF-8 by default. You can also set dependency versions, plugin configurations, resource filters, and other configuration parameters. A full list of available settings can be found in the Maven documentation. Setting the correct values ​​in this section is important for the correct operation of the project and dependency management.

Properties in Maven work as follows: you specify the required data in the pom.xml file, and then use a construct with the name of the property you created in the format ${properties_name} in the required places. This allows you to easily reference values ​​in pom.xml. In Java classes, property values ​​are accessed through getters. This approach simplifies configuration management and makes the code more readable and maintainable.

The dependencies section defines your project's dependencies, that is, the libraries that will be used in development. In this case, only one dependency is specified - JUnit version 3.8.1. For each library in this section, you must specify the groupId, artifactId, and version identifiers. This allows you to manage library versions and simplifies the project build process. Properly specifying dependencies is key to ensuring the stable operation of an application and its compatibility with various libraries.

Scope determines the purpose of a library in the project. In this case, we specified the test scope, which means JUnit will be available exclusively for running tests and will not be included in the main application code. Using test libraries like JUnit helps keep the main code clean and optimizes the project build, minimizing its size and improving performance.

Run the project by clicking the Run button in the App.java window. This will allow you to see the results of the application and test its functionality. Make sure all required dependencies and settings are in place before running.

Screenshot: Skillbox Media

Text displayed successfully: Hello World!

Screenshot: Skillbox Media

Congratulations! You have successfully created your first project using Maven. This is an important step in mastering Java project management. Maven allows you to effectively manage dependencies, automate builds, and simplify the development process. Now you can continue exploring Maven's capabilities, such as creating and customizing POM files, working with repositories, and integrating with other development tools. Good luck with your future projects!

Maven Repositories

Maven is a tool that not only outputs data to the console but also offers powerful capabilities thanks to libraries that can be integrated into a project. Repositories are the primary mechanism for connecting these libraries. With Maven, developers can easily manage dependencies, simplifying the process of building and deploying applications. Using repositories allows you to obtain the latest versions of libraries and keep your project up-to-date.

Maven repositories are repositories for libraries and dependencies used in project builds. They can be compared to Google Play or the App Store, but for developers working with Maven. There are two types of repositories: local and remote. Remote repositories, in turn, are divided into public, accessible to all developers, and third-party, which may contain specific libraries for certain projects or organizations. Effective use of Maven repositories simplifies dependency management and simplifies the application build process.

A local repository is located on your computer and serves as a repository for libraries used in Maven projects. In this repository, Maven stores the dependencies needed to build and develop applications, simplifying the process of managing libraries and their versions.

When you first download a library, Maven stores it in a local repository. This allows subsequent projects to use the version already downloaded, which significantly saves time, since re-downloading is not required.

The public, or central, repository is the main repository of libraries used in Apache Maven. This repository serves as the standard source for the builder, which accesses it by default to obtain the necessary dependencies. Using a central repository simplifies the process of library management and provides access to the latest versions of software components.

Third-party repositories are sources of libraries provided by various organizations or communities. In order for Maven to find and download libraries from these repositories, the appropriate configuration is required. Setting up third-party repositories in Maven allows you to expand your dependency management capabilities and provide access to necessary libraries that are not found in the official repositories.

Libraries can be in two states: snapshot and release. Snapshots represent versions of libraries that are currently under development. They can be modified without changing the version number, which can lead to unpredictable issues, as library functionality may change despite the version remaining the same. Releases, on the other hand, are stable versions of libraries that are not subject to change and are released under a fixed number. It is recommended to use releases to ensure the reliability and stability of your project.

Maven's repository settings are stored in the settings.xml file. This file is located in the conf folder in the directory where Maven is installed. Properly configured settings.xml allows you to manage access to remote repositories and configure local settings, such as proxy servers, mirrors, and repository access credentials. Please note that setting up this file correctly is critical to successful builds and dependency management in your projects.

Screenshot: Skillbox Media

Open the settings.xml file with any text editor. This file contains many lines of code, but we are interested in a specific section. In the default configuration, it looks like this:

ID is a unique identifier for this mirror and, in this case, is set to maven-default-http-blocker. This configuration is designed to block external repositories that use the HTTP protocol. It is especially useful when you need to work exclusively with local repositories, which helps improve the security and reliability of the development process. Using local repositories prevents potential problems associated with accessing external sources and provides a more controlled environment for managing project dependencies.

The mirrorOf element defines which repositories will be mirrored. In our case, the external:http:* pattern is set, which means that the builder will block all external repositories that use the HTTP protocol without exception. This ensures security and control over external dependencies, eliminating potential risks associated with insecure connections.

The name and description of the mirror play a key role in its perception by users. A good name helps attract attention and better understand what exactly the mirror is. The description should be concise and informative to clearly convey the functionality and features of the mirror. Use keywords that reflect the main features and benefits of the product to improve its visibility in search engines. Remember that a well-thought-out name and description not only increase interest but also contribute to increased sales.

The mirror URL is the address where a copy of the web resource is available. In this example, the fictitious URL http://0.0.0.0/ is used as a placeholder. Mirrors can be useful for ensuring the availability of a site if its main address is unavailable. Using mirrors improves stability and page loading speed, and also provides users with alternative ways to access the information they need.

The blocked parameter specifies whether the specified mirror is blocked. In our case, the value is set to true, which means access to external repositories is restricted.

To configure Maven to search for libraries in additional repositories, you must add the appropriate block to the configuration file. This will allow Maven to find and download the required dependencies from the sources you specified. Make sure you specify the repository URLs correctly and use the latest versions of the libraries. Properly configuring repositories in Maven will greatly simplify dependency management and speed up the project build process.

In the URL field, enter the address of the desired repository. After that, Maven will be able to successfully discover it.

What to remember

When gathering information about the project builder, several key aspects can be highlighted. A project builder is a tool that automates the process of building, compiling, and packaging applications. It helps developers streamline their workflow by reducing the time spent on routine tasks. Builders can handle various types of resources, such as JavaScript, CSS, and images, ensuring they are minified and optimized for web projects.

Furthermore, project builders support various configurations, which allows you to tailor the build process to the specific requirements of your application. They integrate with version control systems, simplifying collaboration among development teams. Modern builders offer plugins and extensions, making them flexible and customizable to meet specific project needs.

Ultimately, using a project builder significantly simplifies development, improves application performance, and ensures a higher-quality end product. Understanding how builders work and choosing the right tool are important steps towards effective project management.

  • Maven simplifies the routine tasks of building projects in Java and some other programming languages.
  • Maven's main strength is its POM files, which allow you to fine-tune the project build, taking into account all the libraries and frameworks used.
  • Repositories are used to store libraries. They can be local, that is, located on your computer, or remote. This allows you to flexibly configure access to libraries and use the versions you need.

Learn more about programming and coding in our Telegram channel. Subscribe to receive relevant materials and useful tips!

Read also:

  • Abstract classes in Java and their differences from interfaces
  • Test. Which language will you create - Java or Python?
  • HashMap in Java: what is it and why is it needed?