Scope provided maven что значит

Maven зависимости, dependency

Редко когда какой-либо проект обходится без дополнительных библиотек. Как правило, используемые в проекте библиотеки необходимо включить в сборку, если это не проект OSGi или WEB (хотя и для них зачастую приходится включать в проект отдельные библиотеки). Для решения данной задачи в maven-проекте необходимо использовать зависимость dependency, устанавливаемые в файле pom.xml, где для каждого используемого в проекте артефакта необходимо указать :

  • параметры GAV (groupId, artifactId, version) и, в отдельных случаях, «необязательный» классификатор classifier;
  • области действия зависимостей scope (compile, provided, runtime, test, system, import);
  • месторасположение зависимости (для области действия зависимости system).

Параметры GAV

  • groupId — идентификатор производителя объекта. Часто используется схема принятая в обозначении пакетов Java. Например, если производитель имеет домен domain.com, то в качестве значения groupId удобно использовать значение com.domain. То есть, groupId это по сути имя пакета.
  • artifactId — идентификатор объекта. Обычно это имя создаваемого модуля или приложения.
  • version — версия описываемого объекта. Для незавершенных проектов принято добавлять суффикс SNAPSHOT. Например 1.0.0-SNAPSHOT.

Значения идентификаторов groupId и artifactId подключаемых библиотек практически всегда можно найти на сайте www.mvnrepository.com. Если найти требуемую библиотеку в этом репозитории не удается, то можно использовать дополнительный репозиторий http://repo1.maven.org/maven2.

Cтруктура файла pom.xml и описание секции подключения к проекту репозитория представлены на главной странице фреймворка maven.

Читайте также:  Робить это что значит

Объявление зависимостей заключено в секции . . Количество зависимостей не ограничено. В следующем примере представлено объявление зависимости библиотеки JSON, в которой используется классификатор classifier (в противном случае библиотека не будет найдена в центральном репозитории) :

Классификатор classifier

Классификатор classifier используется в тех случаях, когда деление артефакта по версиям является недостаточным. К примеру, определенная библиотека (артефакт) может быть использована только с определенной JDK (VM), либо разработана под windows или linux. Определять этим библиотекам различные версии – идеологически не верно. Но вот использованием разных классификаторов можно решить данную проблему.

Значение classifier добавляется в конец наименования файла артефакта после его версии перед расширением. Для представленного выше примера полное наименование файла имеет следующий вид : json-lib-2.4-jdk15.jar.

Расположение артефакта в репозитории

В maven-мире «оперируют», как правило, артефактами. Это относится и к создаваемому разработчиком проекту. Когда выполняется сборка проекта, то формируется наименование файла, в котором присутствуют основные параметры GAV. После сборки этот артефакт готов к установке как в локальный репозиторий для использования в других проектах, так и для распространения в public-репозитории. Помните, что в начале файла pom.xml указываются параметры GAV артефакта :

Формально координата артефакта представляет четыре слова, разделенные знаком двоеточия в следующем порядке groupId:artifactId:packaging:version.

Полный путь, по которому находится файл артефакта в локальном репозитории, использует указанные выше четыре характеристики. В нашем примере для зависимости JSON это будет «HOME_PATH/.m2/repository/net/sf/json-lib/json-lib/2.4/json-lib-2.4-jdk15.jar». Параметру groupId соответствует директория (net/sf/json-lib) внутри репозитория (/.m2/repository). Затем идет поддиректория с artifactId (json-lib), внутри которой располагается поддиректория с версией (2.4). В последней располагается сам файл, в названии которого присутствуют все параметры GAV, а расширение файла соогласуется с параметром packaging.

Здесь следует заметить, что правило, при котором «расширение файла с артефактом соответствует его packaging» не всегда верно. К примеру, те, кто знаком с разработкой enterprise приложений, включающих бизнес-логику в виде ejb-модулей и интерфейса в виде war-модулей, знают, что модули ejb-внешне представляют собой обычный архивный файл с расширением jar, хотя в теге packaging определено значение ejb.

В каталоге артефакта, помимо самого файла, хранятся связанные с ним файлы с расширениями *.pom, *.sha1 и *.md5. Файл *.pom содержит полное описание сборки артефакта, а в файлах с расширениями sha1, md5 хранятся соответствующие значения MessageDidgest, полученные при загрузке артефакта в локальный репозиторий. Если исходный файл в ходе загрузки по открытым каналам Internet получил повреждения, то вычисленное значения sha1 и md5 будут отличаться от загруженного значения. А, следовательно, maven должен отвергнуть такой артефакт и попытаться загрузить его из другого репозитория.

Область действия зависимости, scope

Область действия scope определяет этап жизненного цикла проекта, в котором эта зависимость будет использоваться.

test
Если зависимость junit имеет область действия test, то эта зависимость будет использована maven’ом при выполнении компиляции той части проекта, которая содержит тесты, а также при запуске тестов на выполнение и построении отчета с результатами тестирования кода. Попытка сослаться на какой-либо класс или функцию библиотеки junit в основной части приложения (каталог src/main) вызовет ошибку.

compile
К наиболее часто используемой зависимости относится compile (используется по умолчанию). Т.е. dependency, помеченная как compile, или для которой не указано scope, будет доступна как для компиляции основного приложения и его тестов, так и на стадиях запуска основного приложения или тестов. Чтобы инициировать запуск тестов из управляемого maven-проекта можно выполнив команду «mvn test», а для запуска приложения используется плагин exec.

provided
Область действия зависимости provided аналогична compile, за исключением того, что артефакт используется на этапе компиляции и тестирования, а в сборку не включается. Предполагается, что среда исполнения (JDK или WEB-контейнер) предоставят данный артефакт во время выполнения программы. Наглядным примером подобных артефактов являются такие библиотеки, как hibernate или jsf, которые необходимы на этапе разработки приложения.

runtime
Область действия зависимости runtime не нужна для компиляции проекта и используется только на стадии выполнения приложения.

system
Область действия зависимости system аналогична provided за исключением того, что содержащий зависимость артефакт указывается явно в виде абсолютного пути к файлу, определенному в теге systemPath. Обычно к таким артефактам относятся собственные наработки, и искать их в центральном репозитории, куда Вы его не размещали, не имеет смысла :

Версия SNAPSHOT

При определении версии релиза можно использовать SNAPSHOT, который будет свидетельствовать о том, что данный артефакт находится в процессе разработки и в него вносятся постоянные изменения, например делается bugfixing или дорабатывается функционал. В этом случае код и функциональность артефакта последней сборки в репозитории могут не соответствовать реальному положению дел. Таким образом нужно четко отделять стабильные версии артефактов от не стабильных. Связываясь с нестабильными артефактами нужно быть готовыми к тому, что их поведение может измениться и наш проект, использующий такой артефакт, может вызывать исключения. Следовательно, нужно определиться с вопросом: нужно ли обновлять из репозитория артефакт, ведь его номер формально остался неизменным.

Если версия модуля определяется как SNAPSHOT (версия 2.0.0-SNAPSHOT), то maven будет либо пересобирать его каждый раз заново вместо того, чтобы подгружать из локального репозитория, либо каждый раз загружать из public-репозитория. Указывать версию как SNAPSHOT нужно в том случае, если проект в работе и всегда нужна самая последняя версия.

Транзитивные зависимости

Начиная со второй версии фреймворка maven были введены транзитивные зависимости, которые позволяет избегать необходимости изучения и определения библиотек, которые требуются для самой зависимости. Maven включает их автоматически. В общем случае, все зависимости, используемые в проекте, наследуются от родителей. Ограничений по уровню наследований не существует, что, в свою очередь, может вызвать их сильный рост. В качестве примера можно рассмотреть создание проекта «A», который зависит от проекта «B». Но проект «B», в свою очередь, зависит от проекта «C». Подобная цепочка зависимостей может быть сколь угодно длинной. Как в этом случае поступает maven и как связан проект «A» и c проектом «C».

В следующей табличке, позаимствованной с сайта maven, представлен набор правил переноса области scope. К примеру, если scope артефакта «B» compile, а он, в свою очередь, подключает библиотеку «C» как provided, то наш проект «A» будет зависеть от «C» так как указано в ячейке находящейся на пересечении строки «compile» и столбца «provided».

Compile Provided Runtime Test
Compile Compile Runtime
Provided Provided Provided Provided
Runtime Runtime Runtime
Test Test Test Test

Плагин dependency

Имея приведенную выше таблицу правил переноса scope и набор соответствующих артефактам файлов pom можно построить дерево зависимостей для каждой из фаз жизненного цикла проекта. Строить вручную долго и сложно. Можно использовать maven-плагин dependency и выполнить команду «mvn dependency:list», в результате выполнения которой получим итоговый список артефактов и их scope :

Однако к такому списку могут возникнуть вопросы : откуда взялся тот или иной артефакт? Т.е. желательно показать транзитные зависимости. И вот, команда «mvn dependency:tree» позволяет сформировать такое дерево зависимостей :

Плагин dependency содержит большое количество целей goal, к наиболее полезным из которых относятся :

  • dependency:list – выводит список зависимостей и области их действия scope;
  • dependency:tree – выводит иерархический список зависимостей и области их действия scope;
  • dependency:purge-local-repository – служит для удаления из локального репозитория всех артефактов, от которых прямо или косвенно зависит проект. После этого удаленные артефакты загружаются из Internet заново. Это может быть полезно в том случае, когда какой-либо артефакт был загружен со сбоями. В этом случае проще очистить локальный репозиторий и попробовать загрузить библиотеки заново;
  • dependency:sources — служит для загрузки из центральных репозиториев исходников для всех артефактов, используемых в проекте. Порой отлаживая код, часто возникает необходимость подсмотреть исходный код какой-либо библиотеки;
  • dependency:copy-dependencies — копирует зависимости/артефакты в поддиректорию target/dependency;
  • dependency:get — копирует зависимость в локальный репозиторий.

Копирование зависимости в локальный репозиторий

Следующий команда загрузит библиотеку JFreeChart (версия 1.0.19) в локальный репозиторий.

Источник

Scope provided maven что значит

Introduction to the Dependency Mechanism

Dependency management is a core feature of Maven. Managing dependencies for a single project is easy. Managing dependencies for multi-module projects and applications that consist of hundreds of modules is possible. Maven helps a great deal in defining, creating, and maintaining reproducible builds with well-defined classpaths and library versions.

Learn more about:

Transitive Dependencies

Maven avoids the need to discover and specify the libraries that your own dependencies require by including transitive dependencies automatically.

This feature is facilitated by reading the project files of your dependencies from the remote repositories specified. In general, all dependencies of those projects are used in your project, as are any that the project inherits from its parents, or from its dependencies, and so on.

There is no limit to the number of levels that dependencies can be gathered from. A problem arises only if a cyclic dependency is discovered.

With transitive dependencies, the graph of included libraries can quickly grow quite large. For this reason, there are additional features that limit which dependencies are included:

    Dependency mediation — this determines what version of an artifact will be chosen when multiple versions are encountered as dependencies. Maven picks the «nearest definition». That is, it uses the version of the closest dependency to your project in the tree of dependencies. You can always guarantee a version by declaring it explicitly in your project’s POM. Note that if two dependency versions are at the same depth in the dependency tree, the first declaration wins.

      «nearest definition» means that the version used will be the closest one to your project in the tree of dependencies. Consider this tree of dependencies:

    In text, dependencies for A, B, and C are defined as A -> B -> C -> D 2.0 and A -> E -> D 1.0, then D 1.0 will be used when building A because the path from A to D through E is shorter. You could explicitly add a dependency to D 2.0 in A to force the use of D 2.0, as shown here:

    Although transitive dependencies can implicitly include desired dependencies, it is a good practice to explicitly specify the dependencies your source code uses directly. This best practice proves its value especially when the dependencies of your project change their dependencies.

    For example, assume that your project A specifies a dependency on another project B, and project B specifies a dependency on project C. If you are directly using components in project C, and you don’t specify project C in your project A, it may cause build failure when project B suddenly updates/removes its dependency on project C.

    Another reason to directly specify dependencies is that it provides better documentation for your project: one can learn more information by just reading the POM file in your project, or by executing mvn dependency:tree.

    Maven also provides dependency:analyze plugin goal for analyzing the dependencies: it helps making this best practice more achievable.

    Dependency Scope

    Dependency scope is used to limit the transitivity of a dependency and to determine when a dependency is included in a classpath.

    There are 6 scopes:

    • compile
      This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.
    • provided
      This is much like compile , but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. A dependency with this scope is added to the classpath used for compilation and test, but not the runtime classpath. It is not transitive.
    • runtime
      This scope indicates that the dependency is not required for compilation, but is for execution. Maven includes a dependency with this scope in the runtime and test classpaths, but not the compile classpath.
    • test
      This scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases. This scope is not transitive. Typically this scope is used for test libraries such as JUnit and Mockito. It is also used for non-test libraries such as Apache Commons IO if those libraries are used in unit tests (src/test/java) but not in the model code (src/main/java).
    • system
      This scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.
    • import
      This scope is only supported on a dependency of type pom in the section. It indicates the dependency is to be replaced with the effective list of dependencies in the specified POM’s section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.

    Each of the scopes (except for import ) affects transitive dependencies in different ways, as is demonstrated in the table below. If a dependency is set to the scope in the left column, a transitive dependency of that dependency with the scope across the top row results in a dependency in the main project with the scope listed at the intersection. If no scope is listed, it means the dependency is omitted.

    compile provided runtime test
    compile compile(*) runtime
    provided provided provided
    runtime runtime runtime
    test test test

    (*) Note: it is intended that this should be runtime scope instead, so that all compile dependencies must be explicitly listed. However, if a library you depend on extends a class from another library, both must be available at compile time. For this reason, compile time dependencies remain as compile scope even when they are transitive.

    Dependency Management

    The dependency management section is a mechanism for centralizing dependency information. When you have a set of projects that inherit from a common parent, it’s possible to put all information about the dependency in the common POM and have simpler references to the artifacts in the child POMs. The mechanism is best illustrated through some examples. Given these two POMs which extend the same parent:

    These two example POMs share a common dependency and each has one non-trivial dependency. This information can be put in the parent POM like this:

    Then the two child POMs become much simpler:

    NOTE: In two of these dependency references, we had to specify the element. This is because the minimal set of information for matching a dependency reference against a dependencyManagement section is actually . In many cases, these dependencies will refer to jar artifacts with no classifier. This allows us to shorthand the identity set to , since the default for the type field is jar , and the default classifier is null.

    A second, and very important use of the dependency management section is to control the versions of artifacts used in transitive dependencies. As an example consider these projects:

    When maven is run on project B, version 1.0 of artifacts a, b, c, and d will be used regardless of the version specified in their POM.

    • a and c both are declared as dependencies of the project so version 1.0 is used due to dependency mediation. Both also have runtime scope since it is directly specified.
    • b is defined in B’s parent’s dependency management section and since dependency management takes precedence over dependency mediation for transitive dependencies, version 1.0 will be selected should it be referenced in a or c’s POM. b will also have compile scope.
    • Finally, since d is specified in B’s dependency management section, should d be a dependency (or transitive dependency) of a or c, version 1.0 will be chosen — again because dependency management takes precedence over dependency mediation and also because the current POM’s declaration takes precedence over its parent’s declaration.

    The reference information about the dependency management tags is available from the project descriptor reference.

    Importing Dependencies

    The examples in the previous section describe how to specify managed dependencies through inheritance. However, in larger projects it may be impossible to accomplish this since a project can only inherit from a single parent. To accommodate this, projects can import managed dependencies from other projects. This is accomplished by declaring a POM artifact as a dependency with a scope of «import».

    Assuming A is the POM defined in the preceding example, the end result would be the same. All of A’s managed dependencies would be incorporated into B except for d since it is defined in this POM.

    In the example above Z imports the managed dependencies from both X and Y. However, both X and Y contain dependency a. Here, version 1.1 of a would be used since X is declared first and a is not declared in Z’s dependencyManagement.

    This process is recursive. For example, if X imports another POM, Q, when Z is processed it will simply appear that all of Q’s managed dependencies are defined in X.

    Bill of Materials (BOM) POMs

    Imports are most effective when used for defining a «library» of related artifacts that are generally part of a multiproject build. It is fairly common for one project to use one or more artifacts from these libraries. However, it has sometimes been difficult to keep the versions in the project using the artifacts in synch with the versions distributed in the library. The pattern below illustrates how a «bill of materials» (BOM) can be created for use by other projects.

    The root of the project is the BOM POM. It defines the versions of all the artifacts that will be created in the library. Other projects that wish to use the library should import this POM into the dependencyManagement section of their POM.

    The parent subproject has the BOM POM as its parent. It is a normal multiproject pom.

    Next are the actual project POMs.

    The project that follows shows how the library can now be used in another project without having to specify the dependent project’s versions.

    Finally, when creating projects that import dependencies, beware of the following:

    • Do not attempt to import a POM that is defined in a submodule of the current POM. Attempting to do that will result in the build failing since it won’t be able to locate the POM.
    • Never declare the POM importing a POM as the parent (or grandparent, etc) of the target POM. There is no way to resolve the circularity and an exception will be thrown.
    • When referring to artifacts whose POMs have transitive dependencies, the project needs to specify versions of those artifacts as managed dependencies. Not doing so results in a build failure since the artifact may not have a version specified. (This should be considered a best practice in any case as it keeps the versions of artifacts from changing from one build to the next).

    System Dependencies

    Important note: This is deprecated.

    Dependencies with the scope system are always available and are not looked up in repository. They are usually used to tell Maven about dependencies which are provided by the JDK or the VM. Thus, system dependencies are especially useful for resolving dependencies on artifacts which are now provided by the JDK, but were available as separate downloads earlier. Typical examples are the JDBC standard extensions or the Java Authentication and Authorization Service (JAAS).

    Источник

Оцените статью