что такое mojo java

Что такое mojo java

Introduction

Maven plugins can be written in Java or any of a number of scripting languages. Plugins consists of one or more Mojos, each one being the implementation for one of the plugin’s goals. Maven tries to stay out of the way of the programmer with its new Mojo API. This opens up the opportunity for many Mojos to be reused outside of Maven, or bridged into Maven from external systems like Ant.

NOTE: For now, we will limit the discussion to Java-based Mojos, since each scripting language will present these same basic requirements with various forms of implementation.

To serve as a quick reference for the developer, the rest of this page will document these features (the API, along with the annotations) which are considered the best practice for developing Mojos.

API Documentation

org.apache.maven.plugin.Mojo

This interface forms the contract required for Mojos to interact with the Maven infrastructure. It features an execute() method, which triggers the Mojo’s build-process behavior, and can throw a MojoExecutionException if an error condition occurs. See below for a discussion on proper use of this Exception class. Also included is the setLog(..) method, which simply allows Maven to inject a logging mechanism which will allow the Mojo to communicate to the outside world through standard Maven channels.

Method Summary:

Inject a standard Maven logging mechanism to allow this Mojo to communicate events and feedback to the user.

org.apache.maven.plugin.AbstractMojo

Method Summary:

Inject a standard Maven logging mechanism to allow this Mojo to communicate events and feedback to the user.

Furnish access to the standard Maven logging mechanism which is managed in this base class.

Perform whatever build-process behavior this Mojo implements. See the documentation for Mojo above for more information.

org.apache.maven.plugin.logging.Log

Method Summary:

Send a message to the user in the debug error level.

Send a message (and accompanying exception) to the user in the debug error level. The error’s stacktrace will be output when this error level is enabled.

Send an exception to the user in the debug error level. The stack trace for this exception will be output when this error level is enabled.

Send a message to the user in the info error level.

Send a message (and accompanying exception) to the user in the info error level. The error’s stacktrace will be output when this error level is enabled.

Send an exception to the user in the info error level. The stack trace for this exception will be output when this error level is enabled.

Send a message to the user in the warn error level.

Send a message (and accompanying exception) to the user in the warn error level. The error’s stacktrace will be output when this error level is enabled.

Send an exception to the user in the warn error level. The stack trace for this exception will be output when this error level is enabled.

Send a message to the user in the error error level.

Send a message (and accompanying exception) to the user in the error error level. The error’s stacktrace will be output when this error level is enabled.

Send an exception to the user in the error error level. The stack trace for this exception will be output when this error level is enabled.

The Descriptor and Annotations

In addition to the normal Java requirements in terms of interfaces and/or abstract base classes which need to be implemented, a plugin descriptor must accompany these classes inside the plugin jar. This descriptor file is used to provide metadata about the parameters and other component requirements for a set of Mojos so that Maven can initialize the Mojo and validate its configuration before executing it. As such, the plugin descriptor has a certain set of information that is required for each Mojo specification to be valid, as well as requirements for the overall plugin descriptor itself.

Each Mojo specified inside a plugin descriptor must provide the following (annotations specified here are at the class level):

No. Default: per-lookupSpecify the instantiation strategy.phase@phase

NoDefines a default phase to bind a mojo execution to if the user does not explicitly set a phase in the POM. Note: This annotation will not automagically make a mojo run when the plugin declaration is added to the POM. It merely enables the user to omit the

Each Mojo specifies the parameters that it expects in order to work. These parameters are the Mojo’s link to the outside world, and will be satisfied through a combination of POM/project values, plugin configurations (from the POM and configuration defaults), and System properties.

NOTE[1]: For this discussion on Mojo parameters, a single annotation may span multiple elements in the descriptor’s specification for that parameter. Duplicate annotation declarations in this section will be used to detail each parameter of an annotation separately.

NOTE[2]: In many cases, simply annotating a Mojo field with @parameter will be enough to allow injection of a value for that parameter using POM configuration elements. The discussion below shows advanced usage for this annotation, along with others.

Each parameter for a Mojo must be specified in the plugin descriptor as follows:

maven-plugin-plugin 3.x:
@parameter property=»aSystemProperty» default-value=»$«No

Specifies the expressions used to calculate the value to be injected into this parameter of the Mojo at buildtime.

NOTE: If neither default-value nor property or expression are specified, the parameter can only be configured from the POM. The use of ‘$<' and '>‘ in default value is required to delimit actual expressions which may be evaluated.

The final component of a plugin descriptor is the dependencies. This enables the plugin to function independently of its POM (or at least to declare the libraries it needs to run). Dependencies are taken from the runtime scope of the plugin’s calculated dependencies (from the POM). Dependencies are specified in exactly the same manner as in the POM, except for the element (all dependencies in the plugin descriptor are assumed to be runtime, because this is a runtime profile for the plugin).

Plugin Tools

By now, we’ve mentioned the plugin tools several times without telling you what they are or how to use them. Instead of manually writing (and maintaining) the metadata detailed above, Maven ships with some tools to aid in this task. In fact, the only thing a plugin developer needs to do is declare his project to be a plugin from within the POM. Once this is done, Maven will call the appropriate descriptor generators, etc. to produce an artifact that is ready for use within Maven builds. Optional metadata can be injected via Javadoc annotation (and possibly JDK5 annotations in the future) as described above, enabling richer interactions between the Mojo and the user. The section below describes the changes to the POM which are necessary to create plugin artifacts.

Project Descriptor (POM) Requirements

From the POM, Maven plugin projects look quite similar to any other project. For pure Java plugins, the differences are even smaller than for script-based plugins. The following details the POM elements which are necessary to build a Maven plugin artifact.

Источник

Что такое mojo java

This guide is intended to assist users in developing Java plugins for Maven.

Important Notice: Plugin Naming Convention and Apache Maven Trademark

Your First Plugin

In this section we will build a simple plugin with one goal which takes no parameters and simply displays a message on the screen when run. Along the way, we will cover the basics of setting up a project to create a plugin, the minimal contents of a Java mojo which will define goal code, and a couple ways to execute the mojo.

Your First Mojo

At its simplest, a Java mojo consists simply of a single class representing one plugin’s goal. There is no requirement for multiple classes like EJBs, although a plugin which contains a number of similar mojos is likely to use an abstract superclass for the mojos to consolidate code common to all mojos.

When processing the source tree to find mojos, plugin-tools looks for classes with either @Mojo Java 5 annotation or » goal » javadoc annotation. Any class with this annotation are included in the plugin configuration file.

A Simple Mojo

Listed below is a simple mojo class which has no parameters. This is about as simple as a mojo can be. After the listing is a description of the various parts of the source.

All Mojo annotations are described by the Mojo API Specification.

Project Definition

Once the mojos have been written for the plugin, it is time to build the plugin. To do this properly, the project’s descriptor needs to have a number of settings set properly:

groupIdThis is the group ID for the plugin, and should match the common prefix to the packages used by the mojos
artifactIdThis is the name of the plugin
versionThis is the version of the plugin
packagingThis should be set to » maven-plugin «
dependenciesA dependency must be declared to the Maven Plugin Tools API to resolve » AbstractMojo » and related classes

Listed below is an illustration of the sample mojo project’s pom with the parameters set as described in the above table:

Building a Plugin

There are few plugins goals bound to the standard build lifecycle defined with the maven-plugin packaging:

compileCompiles the Java code for the plugin
process-classesExtracts data to build the plugin descriptor
testRuns the plugin’s unit tests
packageBuilds the plugin jar
installInstalls the plugin jar in the local repository
deployDeploys the plugin jar to the remote repository

Executing Your First Mojo

The most direct means of executing your new plugin is to specify the plugin goal directly on the command line. To do this, you need to configure the hello-maven-plugin plugin in you project:

And, you need to specify a fully-qualified goal in the form of:

For example, to run the simple mojo in the sample plugin, you would enter » mvn sample.plugin:hello-maven-plugin:1.0-SNAPSHOT:sayhi » on the command line.

Tips: version is not required to run a standalone goal.

Shortening the Command Line

There are several ways to reduce the amount of required typing:

At this point, you can run the mojo with » mvn hello:sayhi «.

Attaching the Mojo to the Build Lifecycle

You can also configure your plugin to attach specific goals to a particular phase of the build lifecycle. Here is an example:

This causes the simple mojo to be executed whenever Java code is compiled. For more information on binding a mojo to phases in the lifecycle, please refer to the Build Lifecycle document.

Mojo archetype

To create a new plugin project, you could using the Mojo archetype with the following command line:

Parameters

It is unlikely that a mojo will be very useful without parameters. Parameters provide a few very important functions:

Defining Parameters Within a Mojo

Defining a parameter is as simple as creating an instance variable in the mojo and adding the proper annotations. Listed below is an example of a parameter for the simple mojo:

Configuring Parameters in a Project

Configuring the parameter values for a plugin is done in a Maven project within the pom.xml file as part of defining the plugin in the project. An example of configuring a plugin:

In the configuration section, the element name (» greeting «) is the parameter name and the contents of the element (» Welcome «) is the value to be assigned to the parameter.

Note: More details can be found in the Guide to Configuring Plugins.

Parameter Types With One Value

Listed below are the various types of simple variables which can be used as parameters in your mojos, along with any rules on how the values in the POM are interpreted.

Boolean
Integer Numbers
Floating-Point Numbers
Dates
Files and Directories
Plain Text
Enums

Enumeration type parameters can also be used. First you need to define your enumeration type and afterwards you can use the enumeration type in the parameter definition:

So lets have a look like you can use such enumeration in your pom configuration:

You can also use elements from the enumeration type as defaultValues like the following:

Parameter Types With Multiple Values

Listed below are the various types of composite objects which can be used as parameters in your mojos, along with any rules on how the values in the POM are interpreted. In general, the class of the object created to hold the parameter value (as well as the class for each element within the parameter value) is determined as follows (the first step which yields a valid class is used):

Once the type for the element is defined, the text in the XML file is converted to the appropriate type of object

Arrays

Array type parameters are configured by specifying the parameter multiple times. Example:

Collections

For details on the mapping of the individual collection elements, see Mapping Lists.

Properties

in the parameter configuration. Example:

Other Object Classes

Please see Mapping Complex Objects for details on the strategy used to configure those kind of parameters.

Using Setters

You are not restricted to using private field mapping which is good if you are trying to make you Mojos resuable outside the context of Maven. Using the example above we could name our private fields using the underscore convention and provide setters that the configuration mapping mechanism can use. So our Mojo would look like the following:

Note the specification of the property name for each parameter which tells Maven what setter and getter to use when the field’s name does not match the intended name of the parameter in the plugin configuration.

Источник

Что такое MOJO в Maven?

Я читаю о Maven прямо сейчас, и везде в тексте я вижу это слово (mojo). Я примерно понимаю, что это значит, но от хорошего объяснения не отказался бы. Я попытался погуглить, но нашел только не maven объяснения.

POJO-хорошо, но MOJO? Maven старый Java объект?

4 ответа

Как написать программу java (mojo) для распаковки папок в определенном месте? Я новичок в maven, если кто-нибудь поможет мне высоко оценить. /** * The Zip archiver. * @parameter \ expression=$ */ private ZipArchiver zipArchiver; /** * Directory.

Что такое Моджо? Моджо-это Maven простой Старый Java Объект. Каждый моджо-это исполняемая цель в Maven, а плагин-это дистрибутив одного или нескольких связанных моджо.

Короче говоря, моджо-это цель maven, чтобы расширить функциональность, еще не найденную в maven.

Плагин Maven-это артефакт Maven, который содержит дескриптор плагина и один или несколько моджо. Моджо можно рассматривать как цель в Maven, и каждая цель соответствует Моджо. Цель compiler:compile соответствует классу CompilerMojo в плагине компилятора Maven, а цель jar:jar соответствует классу JarMojo в плагине Maven Jar Плагин. Когда вы пишете свой собственный плагин, вы просто группируете набор связанных моджо (или целей) в одном плагине артефакт.

Моджо просто ассоциируется с целью Maven, поэтому мы можем сказать, что Моджо-это гораздо больше, чем просто цель в Maven.

На сайте Maven говорится, что Mojo-это комбинация «Maven» + «POJO (Plain Old Java Object)». Итак, MOJO = Maven Старый объект Java.

Я хотел бы использовать Google Reflections для сканирования классов из скомпилированного проекта из моего плагина Maven. Но плагины по умолчанию не видят скомпилированные классы проекта. Из документации Maven 3 я прочитал: Плагины, которые должны загружать классы из пути к классу.

В maven все делается плагином, у плагина есть один или несколько связанных моджо, т. е. целей.

Моджо-это единая единица задачи в maven.

например : elicpse:eclipse плагин eclipse с целью eclipse-это MOJO

Похожие вопросы:

Я пытаюсь написать плагин maven для выполнения копии, которую я кормлю в Моджо. Это как обертка вокруг данной команды (есть планы расширить ее, чтобы взять любую команду, кроме копирования).

Я хочу позвонить в Моджо help:effective-pom прямо из java/scala. Есть ли минимальный пример того, как настроить maven-runtime и вызвать mojo? Я предполагаю, что необходим некоторый контекст, прежде.

я пишу maven-mojo для пользовательского интеграционного теста. Проблема в том, что теперь мне нужен jar-файл в mojo-исполнении. Если я настрою свой проект для запуска моего пользовательского плагина.

Как написать программу java (mojo) для распаковки папок в определенном месте? Я новичок в maven, если кто-нибудь поможет мне высоко оценить. /** * The Zip archiver. * @parameter \.

Основываясь на документации и почтовых потоках, я видел 3 способа внедрить проект maven в свое Моджо: /** * Project instance * * @parameter default-value=$ * @required * @readonly */.

Я хотел бы использовать Google Reflections для сканирования классов из скомпилированного проекта из моего плагина Maven. Но плагины по умолчанию не видят скомпилированные классы проекта. Из.

Есть ли какой-либо способ получить доступ к свойствам плагинов в методе выполнения? У меня есть базовый Моджо, который обладает некоторыми свойствами, например: @Parameter(defaultValue = DEV.

Источник

В моем Dojo есть Mojo (Как написать плагин Maven)

Я был до моих подмышек, связанных с использованием Maven на работе. Для большого числа разработчиков я услышу «Ну и что?» Разница в том, что я обычно работаю в среде, где у меня нет прямого доступа к Интернету. Поэтому, когда я говорю, что много использую Maven, это что-то значит.

Зависимость ада

Чтобы быть справедливым, я использовал Maven случайно в моих примерах. Я обнаружил, что удобнее загружать зависимости и избегать «ада зависимостей». Ситуация, когда я должен загрузить библиотеку для библиотеки, которую я использую. Например, необходимо загрузить Hamcrest, чтобы использовать JUnit. Дома вставьте зависимость для JUnit, и Maven загрузит Hamcrest для меня, потому что это зависимость от JUnit. Если бы была зависимость от Хэмкреста, Мэйвен тоже загрузил бы это. Когда я на работе, мне нужно исследовать, какие зависимости есть у JUnit, а затем исследовать, какие есть зависимости. Я избегал использования библиотек из-за этой самой ситуации.

Ситуации меняются

Изменение связано с тем, что я использую Spring Roo на работе. Roo использует Maven для управления зависимостями Spring, которые он должен включить. Из-за этого изменения я настроил сервер Nexus в сети разработки и начал процесс переноса зависимостей из Интернета в сеть разработки. Это заставило меня узнать о Maven.

Что я узнал о Maven

Maven — плагин, богатый

Maven основан на архитектуре плагинов. Все, что делает что-то в Maven, является плагином. Это идет от основной функциональности как компиляция к созданию сайтов. Как можно себе представить, каждый плагин имеет определенные общие черты.

Maven ориентирован на пакет, жизненный цикл, фазу и цель

Maven известен тем, что он встраивает что-то в какой-то упакованный предмет, например, файл jar. Это очевидно, это одна из первых строк файла pom. Что может быть неизвестно, так это то, что существует ряд «фаз» или «жизненных циклов», которые выполняют сборку пакета (посмотрите, что я там делал). Фактически, один из этих этапов называется «упаковка». Список фаз по умолчанию в жизненном цикле выглядит следующим образом:

В сборке Maven много чего происходит! Все это выполняется каким-то плагином. Каждый плагин состоит из целей, которые можно настроить на определенную фазу жизненного цикла. Например, цель jar maven-jar-plugin настроена на запуск в фазе пакета.

Создание плагина

Теперь, когда у вас есть более глубокие знания о том, что происходит в сборке, пришло время объяснить, что необходимо для создания плагина Maven.

Плагины полны моджо

Что такое моджо? Mojo — сокращение от Maven, равнина Old Java Objects Это самая маленькая единица в плагине, который распознает Maven. Все плагины сделаны из моджо. Каждое моё связано с целью. Поэтому для того, чтобы плагин имел несколько целей, ему нужно несколько моджо. В примере, который я покажу, к сожалению, есть только одно моджо, но в этом примере также будут показаны лучшие методы тестирования плагина.

Лучшие практики — единственные допустимые практики

Посмотрите, что я сделал там, чтобы связать сделку с додзё в названии? Существует соглашение об именовании, модульное тестирование и интеграционное тестирование, связанные с написанием плагинов, если таковые имеются. Соглашение об именах является наиболее важным, так

Что в имени?

Модульное тестирование

Автоматизированное модульное и интеграционное тестирование также важно. Модульное тестирование следует немного другому шаблону каталога, чем обычное модульное тестирование, поэтому держитесь

Структура каталога при выполнении модульного теста плагина

что такое mojo java. Смотреть фото что такое mojo java. Смотреть картинку что такое mojo java. Картинка про что такое mojo java. Фото что такое mojo java

Обратите внимание, что все тестовые каталоги организованы в тестовом каталоге. То, что вы делаете, это маленькая версия проекта, которая будет использовать плагин. Под каталогом ресурсов тестирования находится каталог модулей, за которым следует имя модуля в дочернем каталоге. Цель состоит в том, чтобы протестировать один модж за раз. Поскольку в моем примере есть только один модж, я настроил только один тест. Существуют и другие отличия, кроме настройки каталога, но они будут рассмотрены в разделе примеров.

Интеграционное тестирование

Я обнаружил, что это тестирование позволит узнать больше о конкретном плагине и о том, как он работает. Цель состоит в том, чтобы протестировать определенную ситуацию, как если бы она была частью реальной сборки проекта. Когда я имею в виду фактическую сборку проекта, я имею в виду, что существует даже временное хранилище только для интеграционной сборки. После прочтения о том, как настроить тесты, я много позаимствовал из настроек интеграционного теста spring-boot-maven-plugin и файлов mini-pom. Хорошо, я скопировал некоторые файлы в мой пример кода. Просто сообщаю, что Spring Boot сделал все правильно. Просто будьте в безопасности клон только для чтения или разветвите их код, чтобы быть в безопасности. Структура каталогов показана ниже.

что такое mojo java. Смотреть фото что такое mojo java. Смотреть картинку что такое mojo java. Картинка про что такое mojo java. Фото что такое mojo java

Интеграционные тесты расположены не под каталогом test, а непосредственно под каталогом src в каталоге it. Я мог бы сделать больше интеграционных тестов, но сейчас достаточно одного.

пример

Пример плагина был вдохновлен тем фактом, что я рассеян и мне нужно напоминать обо всем, что я делаю. Я подумал о создании плагина wash-the-dogs-напоминалки-мавена, но я выбрал простой плагин напоминания-мейвена, потому что тогда я мог использовать его, чтобы напомнить мне обо всем, что мне нужно было сделать.

Источник

Что такое MOJO в Maven?

Я читаю о Maven прямо сейчас и везде в тексте, я вижу это слово (mojo). Я примерно понимаю, что это значит, но я не откажусь от хорошего объяснения. Я попытался Google, но нашел только объяснения, отличные от maven.

POJO – хорошо, но MOJO? Старый объект Java Maven?

Что такое Mojo? Моджо – это простой Java-объект Maven. Каждое mojo является исполняемой целью в Maven, а плагин является распределением одного или нескольких связанных моджо.

Короче говоря, mojo – это цель maven, чтобы расширить функциональность, еще не найденную в maven.

Плагин Maven является артефактом Maven, который содержит дескриптор плагина и один или несколько мохосов. Моджо можно рассматривать как цель в Maven, и каждая цель соответствует Mojo. Цель compiler:compile соответствует классу CompilerMojo в Maven Compiler Plugin, и цель jar:jar соответствует классу JarMojo в Maven Jar Plugin. Когда вы пишете свой собственный плагин, вы просто группируете вместе набор связанных Mojos (или целей) в одном плагине артефакт.

Mojo просто ассоциируется с целью Maven, поэтому мы можем сказать, что Mojo намного больше, чем просто цель в Maven.

сайт Maven говорит, что Mojo – это комбинация “Maven” + “POJO (обычный старый объект Java)”. Итак, MOJO = Старый объект Java Maven.

Но другой, другой ответ на Maven: The Complete Reference, который, как я думаю, принадлежит к той же группе людей, которые управляют сайтом Maven предположим, что Моджо означает Магическое ПОЖО.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *