Add Maven support to an existing project
You can open an existing non-Maven project and add a Maven support via IntelliJ IDEA UI.
Add Maven support
Open an existing project, for example, a Java project.
In the Project tool window, right-click your project and select Add Framework Support .
In the dialog that opens, select Maven from the options on the left and click OK .
IntelliJ IDEA adds a default POM to the project and generates the standard Maven layout in Project tool window.
IntelliJ IDEA also creates a corresponding structure with Lifecycle and Plugins in the Maven tool window.
Open the generated POM and specify a groupId . The artifactId and version are specified automatically.
Every time you change the POM, IntelliJ IDEA displays a popup suggesting to import your changes.
At this point you can further develop your project using Maven. We recommend making all your project changes in POM since IntelliJ IDEA considers pom.xml as a single source of truth.
Create an executable JAR
You can conclude the following optional steps to create an executable JAR.
Click to build project. IntelliJ IDEA generates target folder. Note that IntelliJ IDEA only compiles sources and doesn’t create either JAR file or Manifest file.
Create a Manifest file in the resources directory.
Right-click the directory, select New | Directory to create the META-INF subdirectory. Then right-click the subdirectory, select New | File to create the MANIFEST.MF file.
Open the MANIFEST.MF file in the editor and add information about your main class.
Check the following code:
Alternatively, we can ask Maven to add this line of code into the MANIFEST.MF file with the following code in pom.xml :
In your POM specify the Manifest file information, so you can use Maven to generate an executable jar file.
Alternatively, you can execute package instead of the install command to achieve the same result.
In the Maven tool window, in the Lifecycle list, double-click the install command to generate the jar file. IntelliJ IDEA generates the appropriate information in the target folder and an executable JAR in the Project tool window.
You can right-click the generated JAR and select Run to execute the file.
If the existing project contains more than one module, converting such a project into the Maven project becomes quite challenging. In this case we recommend that you create an external POM where you describe your project and open your POM as you would open a regular Maven project.
Как создать исполняемый JAR с помощью Maven
В этой статье мы рассмотрим упаковку Maven- проекта в файл Jar . Выясним преимущества и недостатки каждого из подходов, применяемых для создания исполняемого файла.
Конфигурация
Чтобы создать исполняемый файл jar , не требуются дополнительные зависимости. Нам нужно просто создать Java-проект Maven с одним классом и методом main(…) .
В приведенном ниже примере мы создаем Java-класс ExecutableMavenJar. Для этого в файл pom.xml нужно добавить следующие элементы:
Удостоверьтесь в том, что в конфигурации задан тип jar . Теперь можно приступить к реализации каждого из подходов.
Ручная настройка
Для этого мы используем плагин maven-dependency-plugin . Сначала скопируем все необходимые зависимости в указанную папку:
Сначала мы задаем цель copy-dependencies , что указывает Maven скопировать эти зависимости в заданный outputDirectory .
В данном случае мы создадим папку с именем libs внутри каталога сборки проекта (обычно это папка target ).
Затем мы создаем исполняемый файл jar с указанными путями к классам и со ссылкой на зависимости, скопированные на первом шаге:
Наиболее важной частью приведенного выше кода является конфигурация manifest . В ней мы добавляем classpath со всеми зависимостями (папка libs/ ), а также предоставляем информацию о главном классе.
Преимущества и недостатки этого подхода:
- Преимущества — прозрачный процесс, в рамках которого можно прописать каждый шаг.
- Недостатки — зависимости находятся вне финального файла jar . Поэтому он будет работать только, если папка libs будет доступна и видима для jar-файла.
Apache Maven Assembly Plugin
Плагин Apache Maven Assembly позволяет объединять выходные данные проекта вместе с зависимостями, модулями, документацией и другими файлами в единый пакет.
Основной целью в плагине сборки является single . Она используется для создания любых сборок. Остальные цели устарели и будут удалены в следующей версии плагина.
Рассмотрим конфигурацию, заданную в файле pom.xml :
Как и при ручной настройке, сначала нужно предоставить информацию о главном классе. Но плагин автоматически скопирует все необходимые зависимости в файл JAR .
В descriptorRefs мы указали имя, которое будет добавлено к имени проекта. В нашем случае – это core-java-jar-with-dependencies.jar.
- Преимущества – зависимости хранятся внутри jar -файла.
- Недостатки — упрощенный контроль упаковки артефакта. Например, нет поддержки перемещения классов.
Apache Maven Shade Plugin
Плагин позволяет упаковывать артефакт в uber-jar , который включает в себя все зависимости, необходимые для запуска проекта. Кроме того, он поддерживает переименование пакетов некоторых зависимостей.
Рассмотрим приведенную ниже конфигурацию:
В этой конфигурации <shadedArtifactAttached> отмечает все зависимости, которые должны быть упакованы в файл jar .
Затем нам нужно указать реализацию трансформатора . В текущем примере мы использовали стандартную версию. В конце задаем основной класс приложения.
Выходной файл получит название core-java-0.1.0-SNAPSHOT-shaded.jar , где core-java — это имя проекта. За ним следуют версия и имя плагина.
- Преимущества — зависимости внутри jar- файла, расширенный контроль упаковки артефакта.
- Недостатки — сложная конфигурация (особенно если необходимо использовать расширенные функции).
One Jar Maven Plugin
Плагин предоставляет собственный загрузчик, который знает, как загружать классы и ресурсы из jar-файлов архива.
Рассмотрим приведенную ниже конфигурацию:
Сначала необходимо указать основной класс и прикрепить все зависимости сборки, используя для этого attachToBuild = true .
Также необходимо задать имя файла для вывода. Цель Maven — это one-jar .
В One Jar зависимости jar не будут расширены в файловую систему во время выполнения.
- Преимущества — позволяет классам располагаться на верхнем уровне One Jar. Плагин поддерживает внешние jar и собственные библиотеки.
- Недостатки – не обновляется с 2012 года.
Плагин Spring Boot Maven
Плагин позволяет упаковывать исполняемые архивы jar или war и запустить приложение «на месте». Он поддерживает Maven версии 3.2 или выше. Более подробное описание плагина доступно здесь .
Рассмотрим приведенную ниже конфигурацию:
Между Spring и другими плагинами есть два существенных отличия: цель выполнения называется repackage , а классификатор — spring-boot . Обратите внимание, что плагин можно использовать без Spring Boot.
- Достоинства – зависимости располагаются внутри jar- файла, его можно запускать в любом доступном месте, улучшенный контроль упаковки артефакта, исключение зависимостей из jar- файла и упаковка war файлов.
- Недостатки — добавляет ненужные классы, связанные с Spring и Spring Boot.
Веб-приложение с исполняемым Tomcat
В последней части статьи мы рассмотрим упаковку автономного веб-приложения в jar -файл. Но для этого понадобится другой плагин.
Чтобы создать jar-файл, запустите man package, который создаст webapp.jar в каталоге target.
Чтобы запустить приложение, просто введите в консоли: java -jar target / webapp.jar и проверьте результат по адресу: localhost:8080/.
- Преимущества — наличие одного файла, простота развертывания и запуска.
- Недостатки — размер файла намного больше.
Обратите внимание на то, что это последняя версия данного плагина, поддерживающая сервер Tomcat7. Чтобы избежать ошибок, обязательно убедитесь в том, что для зависимости Servlets scope задано значение provided. Иначе во время выполнения jar-файла возникнет конфликт:
Заключение
В этой статье мы рассмотрели несколько способов создания исполняемого jar-файла с помощью различных плагинов Maven. Полную реализацию этого руководства вы сможете найти в проектах, опубликованных на Github:
Как проверить? Чтобы скомпилировать проект в исполняемый файл jar , запустите Maven с помощью команды mvn clean package .
Надеемся, что данная статья помогла разобраться в этой теме.
Пожалуйста, опубликуйте свои отзывы по текущей теме материала. Мы крайне благодарны вам за ваши комментарии, лайки, дизлайки, отклики, подписки!
How to Export a JAR from IntelliJ
A JAR (Java archive) file is a platform-independent package of your application in a single archive file. Packaging your application into a JAR makes it easier to distribute your program, and it also means functionalities in your program are reusable—for example, other programs can use your functionalities just by adding your JAR file as a dependency.
There are two types of JARs: normal and executable. Normal JARs have no entry point, meaning you cannot directly execute this type of JAR. You can only add it as a dependency to other programs and access the classes and functions in your program. On the other hand, an executable JAR can be executed directly without any external program. Simply put, you can start an executable JAR directly just by double-clicking on it.
IntelliJ provides a couple different ways to export a JAR from your workspace. In this tutorial, I’ll explain the two different methods for setting up your project architecture to export a JAR from IntelliJ:
- Building an artifact in IntelliJ
- Using Maven
To understand the tutorial better, you’ll use a simple example program that accepts user profile information as a command line argument. This program also uses Picocli and Apache Commons Cli as external dependencies, which will support validating and parsing the command line parameters.
Export a JAR Using the Build Artifact Method
In this method, you’ll export a JAR using the IntelliJ build option. Before starting up, you’ll need to create a project and add the necessary dependencies to it. Dependencies are external programs packaged as a JAR with some functionalities implemented already and can easily be reused in your program. You’ll also need to create a main class with some simple functionality.
Once you’ve created a project and a Run Configuration, which can be used to execute the project, let’s set up your program to export a JAR from the IntelliJ workspace.
1. Configure the project settings to define the artifacts of this project. Click Project Structure from the file menu.
2. In the Project Structure window, click Artifacts in the left pane, then click the plus symbol. Expand the JAR option and click From module with dependencies.
This opens the Create JAR from Modules window.
3. Click the folder icon on the right side of the Main Class field to select the main class of your project. If you know the name of the main class, start typing in the field to see suggestions.
4. Set how external libraries should be handled while creating the JAR. There are two options:
-
- Extract to the target JAR: This option extracts all the class files of your external libraries to the JAR you’re creating. This single JAR will contain your class files and also the class files from your external dependencies. This option is recommended because handling a single JAR is easier than handling multiple. You can easily add it to your other programs and execute it with a double click.
- Copy to the output directory and link via Manifest: This option copies your dependency JARs to the output directory and creates a link with your Java program using the manifest file. If you select this option, you should also specify a location where the manifest file needs to be created. This method is recommended if you have a lot of JARs, and particularly if any of them are signed. Signed JARs may not work properly when you extract the class files into the JAR. Therefore, it’s better to copy the JARs to the output directory and use them via the manifest file.
5. Select the appropriate option and click OK, creating an artifact in your Artifacts window.
You’ll see the name of the JAR in the Name field and its location in the Output directory. You can change the output directory to your desired location.
If you need a JAR to be created during each and every project build, select Include in project build. If you don’t need that, leave the option unselected. In that case, you can build the JAR when you’re done with your project development, using the Build Artifacts option.
When you click Build Artifacts, the JAR is generated in the output directory you’ve selected.
So that’s how you export a JAR using the options available in IntelliJ. Next, you’ll see how to export a JAR using Maven.
Exporting a JAR Using Maven
Maven is a project management and automation tool, developed to make the build process easier. For example, you can create scripts to:
- Build a project and create a JAR after each and every commit to your git repo.
- Build a project nightly and deploy the JARs in the production systems when all the defined test cases are passing.
- Automate build and deployment of projects with Jenkins.
To begin, create a Maven project in IntelliJ using this tutorial. Remember to add the necessary classes for your project. You can use the same class files and dependencies used in the previous section’s example.
When you create a new Maven project, you’ll have the minimal POM file created in your project directory with the following contents:
This POM file contains three important artifacts for the project:
- groupId : A unique base name of the company that creates and maintains the project.
- artifactId : A unique name for the project itself
- version : Version number for the project
Configuring the Maven build
In this section, you’ll configure the aspects of your Maven build. You can add various plugins inside the build section of your POM file based on your requirements. Each will have different functions. These plugins will be executed during the build of your project.
In this tutorial, you’ll add the necessary plugin and configure it to export a JAR during the build.
This adds a Maven compiler for your projects and also denotes the java version for compiling your sources. Here, you’re using Java version 1.8.
2. Add the maven-assembly-plugin . This creates an assembly of your Java project.
For a quick explanation of the plugin’s various sections:
- artifactId : The name of the plugin itself
- configuration : Configures the maven assembly
- finalName : Final name of the assembly to be created : Flag to include or exclude the assembly name in the JAR’s final name : Adds instructions to the archive builder, in this case, adding the main class of your Java program in the manifest : List of references to assembly descriptors available on the plugin’s classpath
- execution : Tag to specify the activities to be performed during execution
- goal : Here, directory-single is used to create a single file during the build
Now that you’ve configured the Maven settings for your project, the whole POM file for the project should look like this:
Executing a Maven Build
Next, you’ll create a configuration for the Maven build and execute it. It’ll export a JAR in the directories you’ve specified.
1. Navigate to Run > Edit Configurations. The Run/Debug Configurations window opens.
2. Select the Maven option from the Add New Configuration menu.
This will create a Maven run configuration for you as below.
3. Give the configuration a name and add the project’s home directory as your home directory.
4. In the command line field, add clean install . These goals stipulate that the projects should be cleaned and the package should be installed in the appropriate directory.
5. Click Apply and OK. This creates a run configuration for you directly.
6. From the Run menu, click Run configuration_name.
You’ll see the build starting in your console, and after a few seconds, you’ll see the message BUILD SUCCESS . The JAR will be in the target directory of your Project home.
Remember, since this project has the configurations in a Pom.xml file, you can also configure an automatic build using Jenkins scripts on any trigger (for example, after every commit to your git repo).
Conclusion
Building a JAR in IntelliJ is a little complicated when it comes to configuring project structure and generating artifacts. In the case of using Maven, it’s even more difficult due to the setup involved with configuring the POM file and the project’s build processes.
But in this tutorial, you learned how to tackle two different options for building a JAR (using the build artifact method and using Maven) in IntelliJ to make the process easier. If you’ve got any suggestions or tips for creating a JAR that this article didn’t cover, please let me know about them in the comments.
Как создать Jar файл в Maven
В этом уроке я покажу вам, как использовать Maven для создания Java проекта и упаковать его в *.jar файл, а также как сделать его исполняемым.
1) Создание Maven проекта.
Есть два способа создать Maven project:
1. С помощью maven command:
2. С иcпользованием IDE, в моем случае это Intellij IDEA 11.3
2. Создание jar файла
Чтобы создать jar файл нам потребуется добавить в конфигурационный Maven файл pom.xml.
В этом файле в теге <pagckaging>jar</pagckaging>
Если вы попытаетесь собрать проект Maven, Maven упакует этот проект в “jar” файл с именем «projectMy-1.0.jar» , найти этот файл вы можете в корне проекта в папке target .