What is Archetype?
In short, Archetype is a Maven project templating toolkit. An archetype is defined as an original pattern or model from which all other things of the same kind are made. The name fits as we are trying to provide a system that provides a consistent means of generating Maven projects. Archetype will help authors create Maven project templates for users, and provides users with the means to generate parameterized versions of those project templates.
Using archetypes provides a great way to enable developers quickly in a way consistent with best practices employed by your project or organization. Within the Maven project, we use archetypes to try and get our users up and running as quickly as possible by providing a sample project that demonstrates many of the features of Maven, while introducing new users to the best practices employed by Maven. In a matter of seconds, a new user can have a working Maven project to use as a jumping board for investigating more of the features in Maven. We have also tried to make the Archetype mechanism additive, and by that we mean allowing portions of a project to be captured in an archetype so that pieces or aspects of a project can be added to existing projects. A good example of this is the Maven site archetype. If, for example, you have used the quick start archetype to generate a working project, you can then quickly create a site for that project by using the site archetype within that existing project. You can do anything like this with archetypes.
You may want to standardize J2EE development within your organization, so you may want to provide archetypes for EJBs, or WARs, or for your web services. Once these archetypes are created and deployed in your organization’s repository, they are available for use by all developers within your organization.
Using an Archetype
To create a new project based on an Archetype, you need to call mvn archetype:generate goal, like the following:
Provided Archetypes
Maven provides several Archetype artifacts:
Archetype ArtifactIds | Description |
---|---|
maven-archetype-archetype | An archetype to generate a sample archetype project. |
maven-archetype-j2ee-simple | An archetype to generate a simplifed sample J2EE application. |
maven-archetype-mojo | An archetype to generate a sample a sample Maven plugin. |
maven-archetype-plugin | An archetype to generate a sample Maven plugin. |
maven-archetype-plugin-site | An archetype to generate a sample Maven plugin site. |
maven-archetype-portlet | An archetype to generate a sample JSR-268 Portlet. |
maven-archetype-quickstart | An archetype to generate a sample Maven project. |
maven-archetype-simple | An archetype to generate a simple Maven project. |
maven-archetype-site | An archetype to generate a sample Maven site which demonstrates some of the supported document types like APT, XDoc, and FML and demonstrates how to i18n your site. |
maven-archetype-site-simple | An archetype to generate a sample Maven site. |
maven-archetype-webapp | An archetype to generate a sample Maven Webapp project. |
For more information on these archetypes, please refer to the Maven Archetype Bundles page.
What makes up an Archetype?
Archetypes are packaged up in a JAR and they consist of the archetype metadata which describes the contents of archetype, and a set of Velocity templates which make up the prototype project. If you would like to know how to make your own archetypes, please refer to our Guide to creating archetypes.
Maven Archetypes Project Templating
I am developer and I like DRY. If there is any task you have to do more than once you should probably automate it. starting a new project, it can be tedious and time-consuming to start over and over again from scratch. You can use Spring Initializr to boostrap your new application or even better without leaving the shell Spring Boot CLI. You will get nice clean project with the latest versions of dependencies but what if you need to use specific internal libraries or configuration files? Wouldn’t be nice to have project template and generate new one by answersing few simple questions? Project generation (scaffolding) was made popular by the Ruby on Rails framework and now we got many generators included in popular frameworks or standalone but if you are already using Maven as you your build tool don’t look any further.
Maven Archetypes
Archetype is a Maven project templating toolkit. An archetype is defined as an original pattern or model from which all other things of the same kind are made. Archetype will help authors create Maven project templates for users, and provides users with the means to generate parameterized versions of those project templates. Using archetypes provides a great way to enable developers quickly in a way consistent with best practices employed by your project or organization.
Maven provides several archetype artifacts.
Creating a Maven Archetype
Creating archetype from scratch is possible but I would recomend pick some existing project and generate archetype from it.
Generated source code can then be found under the target/generated-sources/archetype directory. When you type mvn install in this directory it will install archetype in our local Maven repository ($
Dynamic content
Maven Archetypes use Apache Velocity Engine for incorporating the dynamic content in genereted files. Any file in archetype resources is template but some files need to be escaped because they charcters are used by Velocity. For example XML, Java or Groovy files might use similar characters. You have to define special variable to escape them:
Example from Groovy Script or Jenkins config:
You can also apply variable substitution to file names. To inject a property into a file name, surround the property erty name with “__“.
Defining additional properties
The main properties that are used by the Velocity engine during a project’s file generation are groupId, artifactId, version and package. It is possible to define additional properties that must be valued before the file generation. These additional properties can be provided with default values, which enable not to ask the user for there values. Additional properties are defined in the /src/main/resources/META-INF/maven/archetype-metadata.xml file with:
Defining specific filesets
The filesets contained in the /src/main/resources/META-INF/maven/archetype-metadata.xml file defines the way the project’s files located in the JAR file are used by the Archetype Plugin to generate a project. Filesets must define the directory where the files will be searched for which is also the directory where the project’s files will be generated.This provide a way to describe a large set of files to be selected for the generation process. Filesets can be filtered, which means the selected files will be used as Velocity templates. A fileset is defined in the archetype-metadata.xml with this fragment:
Sample archetype directory structure:
Installing the Archetype
You can install the archetype by invoking this command:
Create a project using archetype
You can create a Maven project through the generate goal and existing archetype.
Run the project
Test on the browser
Full list of available archetypes can be generated using mvn archetype:generate :
Maven In Depth: Creating A Custom Archetype For Spring Boot Project
Hi guys! We gonna take in-depth look at one of the advanced features of Apache Maven and the most I’ve ever liked… we’re going to see together how to create a custom archetype for a Spring Boot project, but first, have you ever encountered problems in managing your java projects? Have you ever had problems within your team with the structure or naming convention of your projects? Are you tired of writing redundant code on a daily basis? Are you a java developer, but a lazy one? If the answer is yes, then a Maven custom archetype is the solution to a large part of your problem.
Before starting! I assume you are familiar with Apache Maven, otherwise you can enjoy this Baeldung tutorial.
Introduction
What is Maven Archetype? How to use it? And how to create a custom one?
Don’t worry, we’ll answer all these questions in this article step by step.
What is Maven Archetype?
Maven archetypes are simply a project templates that can help us quickly create a maven starter project based on its type. It's a great tool to start a maven project with the least amount of effort.
There are wide options of archetypes available to us. Some of the popular archetypes include maven-archetype-quickstart, maven-archetype-webapp, maven-archetype-archetype…
Create a Maven Archetype
To create a maven project with a specific archetype, we can use:
This command will ask us to choose an archetype and will then create our maven project from it.
We can also define our custom archetype. It is specifically helpful when we have multi-module project which share the same structure. We can simply standardize a template to use for creating our modules.
In this article, we will use a Spring Boot multi-module project:
This demo project consists of two modules (starter and sample), the starter module contains our main application and use the sample module as a library.
PS: the code will be available at the end of this article.
Let’s focus a little bit on the demo-sample module:
This module contains a controller package that contains a controller class with a helloWorld() method that returns a hello world message.
For future purpose, we want to make a generic template (Maven Archetype) for our modules, to be used whenever we want to generate new module and avoid recreating each module and their classes from scratch.
To create our own Maven Archetype there are two ways:
Create a Maven Archetype from existing project:
It’s fairly easy to create a Maven archetype from one of our existing modules. All we have to do is run this command from the root directory of our project:
Create a Maven Archetype using a predefined Archetype (maven-archetype-archetype):
We can directly generate an archetype project by using this predefined Maven Archetype called maven-archetype-archetype
mvn archetype:generate -B -DarchetypeArtifactId=maven-archetype-archetype
Either way, after the successful creation of the archetype, we get this archetype generated under /target/generated-sources
Now that we have generated the archetype structure, we can start modifying our generated sources:
- Modify the target/generated-sources/archetype/src/main/resources/archetype-resources/pom.xml to add or remove additional dependencies as needed.
- Modify the target/generated-sources/archetype/pom.xml as we want, we can change the groupId, the artifactId or the version of our generated Archetype.
- Modify our Archetype Metadata file (called also ArchetypeDescriptor). The archetype-metadata.xml stores the metadata of our archetype and is present in the folder target/generated-sources/archetype/src/main/resources/META-INF/maven.
Let’s explain in details the elements of the archetype-metadata file and other global details:
<requiredProperties> tag defines the properties required to generate a project from this archetype. We can specify the default value of the property, as we can also define a regular expression used to validate the entered property.
<fileSet> tag defines where to find the module files to be used in the generation of the archetype project.
filtered = “true” means that placeholders are replaced by the values provided when generating the project and the selected files will be used as Velocity templates.
packaged = “true” means that the selected files will be generated in a directory structure that is prepended by the package property.
If the name of the file or directory contains __property__ pattern or if the file contains $ , it is replaced by the corresponding property value.
Building a Maven Archetype
We can build our archetype project now by going to /generated-sources/archetype and run:
We can find our built jar under /generated-sources/archetype/target and it will be installed in our local Maven repository under /.m2/repository/<group_id>
Using Created Archetype
By now, we have successfully installed our customized archetype. To generate a new “dummy” module from this newly created archetype, we will first switch to our project/demo root directory and then run:
mvn archetype:generate -DarchetypeGroupId=com.example
-DarchetypeArtifactId=demo-custom-archetype
-DarchetypeVersion=1.0-SNAPSHOT
-DgroupId=com.example
-DartifactId=demo-dummy
-Dversion=1.0-SNAPSHOT
Then it will ask us if we want to continue with the default values, otherwise we can enter our desired values as shown below:
As we can see here we set the package, the configName and the controllerName to Dummy with the present of the Regex validation.
After further confirmation, we have our new dummy module in our project:
The last step now is to run this project and test it !
Well done! Our new generated dummy module works perfectly well as the sample module.
Conclusion
Maven Archetype one of the greatest tools given by Maven, it absolutely makes things easier and save us a lot of time. Here we are at the end of this chapter. I hope it was a good and useful experience.
Создание архетипа Maven из существующего проекта
Создайте архетип из существующего проекта и сгенерируйте новые клоны с минимальными усилиями. Прекратите копи-паст проектов и создайте архетип!
Если вы создаете облако микросервисов или находитесь в среде, где вам нужно сгенерировать несколько проектов или модулей maven, очень полезно создавать архетипы для разработки этих новых модулей/проектов.
Что такое архетип?
Архетип maven — это шаблонный проект. Maven предлагает несколько архетипов, которые позволяют создавать новые модули maven, готовые к запуску за несколько секунд.
Как использовать общий архетип?
Использовать архетип довольно просто. Если вы хотите сгенерировать архетип на основе списка по умолчанию, просто запустите:
Затем выберите один из вариантов, укажите детали и подтвердите. Новый проект уже будет создан.
Как использовать стандартный архетип?
В этом случае нам нужно указать groupId и artifactId архетипа, чтобы иметь возможность использовать настраиваемый. В качестве примера давайте посмотрим на архетип, предоставленный Adobe для AEM:
Если вы запустите команду, вас спросят о некоторых свойствах вашего проекта. Некоторые свойства являются стандартными ( groupId , version , artifactId и package ), но другие были специфичны этого артефакта, как appTitle и sdkVersion . Эти свойства помогут архетипу сгенерировать для вас новый проект, и через несколько секунд, ничего не зная об Adobe AEM, вы получите свой новый проект, готовый к запуску.
Как работает архетип?
Внутри архетипа есть все файлы (pom-файл, классы, readme и т. д.) С переменными, которые будут заменены во время генерации проекта. В качестве примера вы можете увидеть эти переменные в нескольких частях файла pom ниже.
В Maven есть хорошая документация, как организовать и создать свой архетип с нуля.
Создание архетипа из проекта
В большинстве случаев поддерживать архетип сложно, потому что:
Это не сам проект, поэтому вам нужно использовать свой архетип, чтобы увидеть, работает ли сгенерированный проект.
Шаблоны — это хорошо, но их трудно читать, и вам нужно «представить», как будет выглядеть код после.
Мы ленивы, и если это трудно понять, то будет сложно поддерживать. Люди вернутся к проектам копирования и вставки и заменят текст.
Простой способ обойти все эти ограничения — создать архетип из примера проекта. Наш примерный проект — это идеальный компилируемый проект со всеми желаемыми конфигурациями, которые мы хотим сохранить вместе в клонах.
Создайте свой пример проекта для архетипа
Некоторые желательные характеристики в проекте примера для архетипа:
Он должен быть простым, но полным. Не забудьте включить все зависимости и по одному примеру каждого элемента вашего проекта. Например, если проект представляет собой микросервис, имеет смысл включить контроллер, службу и репозиторий.
Назовите его связным образом (вы увидите это на следующих шагах). Я бы порекомендовал, например, иметь контроллер под названием ArchetypeExampleController , который общается с ArchetypeExampleService .
В каждом файле поместите один и тот же префикс в переменные, чтобы их было легко заменить. Например, если вам нужна переменная для вашей ArchetypeExampleService , хорошее имя — archetypeVariableService .
Включите dot-файлы как часть этого проекта и хороший файл readme.
archetype:create-from-project
В рамках конфигурации вы можете передать файл archetype.properties в качестве параметра. Этот файл свойств должен выглядеть так:
Как вы видите выше, я включил только изменяющуюся часть файлов или переменных, и maven позаботится о их замене за меня.
Шаг-за-шагом
Давайте пройдем все шаги от нашего примера проекта архетипа до нашего архетипа.
1. Переименуйте все dot-файлы.
Известно, что dot-файлы не включаются в архетип. Поэтому нам нужно переименовать их, чтобы они также были включены в сгенерированный архетип (и последующий проект).
2. Вызовите цель maven с желаемыми параметрами.
В документации вы можете увидеть больше параметров и узнать, почему и когда они используются, но вкратце:
-Dinteractive=false : интерактивный режим отключен.
-DkeepParent=true : оставить родителя.
-DpropertyFile=archetype.properties : используйте наш файл archetype.properties для проверки переменных.
-DpackageName=com.almeida.tomas : имя пакета для источников java, который должен быть включен в архетип.
-Darchetype.filteredExtensions=java,xml,md : файлы с выбранными расширениями будут проверены, а содержимое и имя файлов будут изменены переменными.
3. Очистите сгенерированные метаданные архетипа.
В некоторых случаях генерация включает значение свойства по умолчанию, и мы хотим быть уверены, что все значения будут заполнены пользователем.
4. Установите или разверните архетип.
Если вы запускаете эти команды локально, архетип в вашем локальном репо:
Я рекомендую настроить задание Jenkins, чтобы каждый раз, когда в проект вносится изменение, Jenkins запускает команды и отправляет новую версию в ваш репозиторий.
Используйте созданный вами архетип
Созданный архетип будет иметь такой же artifactId с суффиксом -archetype . Итак, исходя из нашего примера:
Теперь нас попросят указать значение для переменных по умолчанию и персонализированных переменных:
Подтвердите, что значения, которые вы ввели, верны:
Будет создана новая папка с именем artifacId. В нашем примере demo-project .
Необходимо переименовать dot-файлы:
Итак, теперь вы можете создать несколько клонов вашего примера проекта архетипа за считанные минуты!