Setting the java version in maven
Содержание:
- Зависимости и репозитории.
- Apache Maven Assembly Plugin
- Объявление зависимостей
- Spring Boot Specification
- Apache Maven Site Plugin
- Установка Maven.
- Apache Maven Help Plugin
- Создание приложения из архетипа
- Feature Summary
- Apache Maven Deploy Plugin
- Сборка Java кода
- Описание Maven
- Apache Maven PMD Plugin
- Overview
- 2. Use the Compiler Plugin
- 3. Spring Boot Specification
- 4. Conclusion
Зависимости и репозитории.
Большинство популярных библиотек находятся в центральном репозитории , поэтому их можно сразу прописывать в раздел dependencies pom-файла.
Например, чтобы подключить Spring Framework нужно определить зависимость:
<dependencies>
…
<dependency>
<groupId>org.springframework</groupId>
<artifacrId>spring</artifactId>
<version>2.5.5</version>
</dependency>
</dependencies>
Можно не указывать версию, тогда Maven возьмет последний вариант, но рекомендуется это делать.
Специфические вещи не находятся в центральном репозитории и нужно в таких случаях указать репозиторий вручную. К примеру, добавим зависимость JSF-фреймворка ajax-компонентов JBoss RichFaces.
С зависимостями все просто:
<dependencies>
<dependency>
<groupId>org.richfaces.ui>/groupId>
<artifactId>richfaces-ui</artifactId>
<version>3.3.1.GA</version>
</dependency>
</dependencies>
А репозиторий JBoss нужно прописать вручную либо в файле setting.xml в корне локального репозитория, либо в pom.xml, в зависимости от того, нужен ли этот репозиторий во всех проектах или в одном конкретном:
<!— JBoss RichFaces Repository —> <repositories> <repository> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> <updatePolicy>never</updatePolicy> </snapshots> <id>repository.jboss.com</id> <name>Jboss Repository for Maven</name> <url> </url> <layout>default</layout> </repository> </repositories>
Обычно на сайтах крупных проектов пишут все что нужно для встраивания их библиотеки в проект на основе Maven.
Apache Maven Assembly Plugin
Introduction
The Assembly Plugin for Maven enables developers to combine project output into a single distributable archive that also contains dependencies, modules, site documentation, and other files.
Your project can easily build distribution «assemblies» using one of the prefabricated assembly descriptors. These descriptors handle many common operations, such as packaging a project’s artifact along with generated documentation into a . Alternatively, your project can provide its own descriptor and assume a much higher level of control over how dependencies, modules, file-sets, and individual files are packaged in the assembly.
Currently it can create distributions in the following formats:
- zip
- tar
- tar.gz (or tgz)
- tar.bz2 (or tbz2)
- tar.snappy
- tar.xz (or txz)
- jar
- dir
- war
- and any other format that the ArchiveManager has been configured for
If your project wants to package your artifact in an uber-jar, the assembly plugin provides only basic support. For more control, use the Maven Shade Plugin.
To use the Assembly Plugin in Maven, you simply need to:
- choose or write the assembly descriptor to use,
- configure the Assembly Plugin in your project’s pom.xml, and
- run «mvn assembly:single» on your project.
To write your own custom assembly, you will need to refer to the Assembly Descriptor Format reference.
What is an Assembly?
An «assembly» is a group of files, directories, and dependencies that are assembled into an archive format and distributed. For example, assume that a Maven project defines a single JAR artifact that contains both a console application and a Swing application. Such a project could define two «assemblies» that bundle the application with a different set of supporting scripts and dependency sets. One assembly would be the assembly for the console application, and the other assembly could be a Swing application bundled with a slightly different set of dependencies.
The Assembly Plugin provides a descriptor format which allows you to define an arbitrary assembly of files and directories from a project. For example, if your Maven project contains the directory «src/main/bin», you can instruct the Assembly Plugin to copy the contents of this directory to the «bin» directory of an assembly and to change the permissions of the files in the «bin» directory to UNIX mode 755. The parameters for configuring this behavior are supplied to the Assembly Plugin by way of the assembly descriptor.
Goals
The main goal in the assembly plugin is the single goal. It is used to create all assemblies.
For more information about the goals that are available in the Assembly Plugin, see the plugin documentation page.
Assembly and Component Descriptor Schemas (XSD)
- http://maven.apache.org/xsd/assembly-2.0.0.xsd, http://maven.apache.org/xsd/assembly-component-2.0.0.xsd (for version 3.0 and higher)
- http://maven.apache.org/xsd/assembly-1.1.3.xsd, http://maven.apache.org/xsd/component-1.1.3.xsd (for version 2.5.4 and higher)
- http://maven.apache.org/xsd/assembly-1.1.2.xsd, http://maven.apache.org/xsd/component-1.1.2.xsd (for version 2.2 and higher)
- http://maven.apache.org/xsd/assembly-1.1.1.xsd, http://maven.apache.org/xsd/component-1.1.1.xsd (for version 2.2-beta-4 — 2.2-beta-5)
- http://maven.apache.org/xsd/assembly-1.1.0.xsd, http://maven.apache.org/xsd/component-1.1.0.xsd (for version 2.2-beta-1 — 2.2-beta-3)
- http://maven.apache.org/xsd/assembly-1.0.0.xsd, http://maven.apache.org/xsd/component-1.0.0.xsd (for version 2.1 and lower)
Usage
General instructions on how to use the Assembly Plugin can be found on the usage page. Some more specific use cases are described in the examples given below.
If you feel like the plugin is missing a feature or has a defect, you can fill a feature request or bug report in our issue tracker. When creating a new issue, please provide a comprehensive description of your concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, entire debug logs, POMs or most preferably little demo projects attached to the issue are very much appreciated. Of course, patches are welcome, too. Contributors can check out the project from our source repository and will find supplementary information in the guide to helping with Maven.
Examples
To provide you with better understanding on some usages of the Assembly Plugin, you can take a look into the examples which can be found here.
Объявление зависимостей
Простой «Hello World» пример полностью автономный и не зависит от каких-либо дополнительных библиотек.
Однако, большинство приложений зависит от внешних библиотек, с реализацией распостраненного и/или
сложного функционала.
К примеру, предположим, что в дополнение к «Hello World!» вы хотите, чтобы приложение печатало текущую дату и время.
Вы могли бы использовать функциональность из стандартных(native) Java библиотек, но мы можем сделать это
и другими интересными способами, например с помощью Joda Time библиотеки.
Для начала, изменим , как показано ниже:
Здесь использует Joda Time класс для получения и печати текущего времени.
Если бы вы запустили для сборки проекта сейчас, то получили бы ошибку сборки,
потому что вы не объявили Joda Time компилируемую зависимость в сборке. Вы можете это исправить,
добавив следующие строки в pom.xml(в пределах элемента):
Этот блок XML объявляет список зависимостей проекта. В частности, он объявляет единственную зависимость от
Joda Time библиотеки. В элементе, зависимость определяется через описание
трех вложенных элементов:
- — группа или организация, к которой принадлежит зависимость.
- — необходимая библиотека
- — версия необходимой библиотеки
По умолчанию, все зависимости определены как зависимости. Т.е. они должны быть
доступны во время компиляции(а если вы собираете WAR-файл, то в /WEB-INF/lib каталоге). Кроме того,
вы можете добавить элемент, с одним из значений:
-
— зависимости, которые требуются для компиляции кода проекта,
но которые будут доступны во время выполнения кода контейнером(например, Java Servlet API) -
— зависимости, которые используются для компиляции и запуска тестов,
но не требуемые для сборки или выполнения кода проекта
Сейчас, если вы выполните или , Maven должен
будет разрешить Joda Time зависимость из Maven Central репозитория и успешно собрать проект.
Здесь полная версия :
Spring Boot Specification
Spring Boot applications specify the JDK version inside of the properties tags in the pom.xml file.
First, we need to add spring-boot-starter-parent as a parent to our project:
This parent POM allows us to configure default plugins and multiple properties including the Java version — by default, the Java version is 1.8.
However, we can override the default version of the parent by specifying the java.version property:
By setting the java.version property, we declare that the source and the target Java versions are both equal to 1.9.
Above all, we should keep in mind that this property is a Spring Boot Specification. Additionally, starting from Spring Boot 2.0, Java 8 is the minimum version.
This means we can’t use or configure Spring Boot for the older JDK versions.
Apache Maven Site Plugin
The Site Plugin is used to generate a site for the project. The generated site also includes the project’s reports that were configured in the POM.
Please read the migration guide if you want to upgrade from a previous version.
Goals Overview
The Site Plugin has seven goals:
- site:site is used generate a site for a single project. Note that links between module sites in a multi module build will not work, since local build directory structure doesn’t match deployed site.
- site:deploy is used to deploy the generated site using Wagon supported protocol to the site URL specified in the <distributionManagement> section of the POM.
- site:run starts the site up, rendering documents as requested for faster editing. It uses Jetty as the web server.
- site:stage generates a site in a local staging or mock directory based on the site URL specified in the <distributionManagement> section of the POM. It can be used to test that links between module sites in a multi module build work. This goal requires the site to already have been generated using the site goal, such as by calling mvn site.
- site:stage-deploy deploys the generated site to a staging or mock directory to the site URL specified in the <distributionManagement> section of the POM.
- site:attach-descriptor adds the site descriptor (site.xml) to the list of files to be installed/deployed. For more references of the site descriptor, here’s a link.
- site:jar bundles the site output into a JAR so that it can be deployed to a repository.
- site:effective-site calculates the effective site descriptor, after inheritance and interpolation.
Usage
General instructions on how to use the Site Plugin can be found on the usage page. Some more specific use cases are described in the examples given below.
If you feel like the plugin is missing a feature or has a defect, you can file a feature request or bug report in our issue tracker. When creating a new issue, please provide a comprehensive description of your concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, entire debug logs, POMs, or, most preferably, little demo projects attached to the issue are very much appreciated. Of course, patches are welcome, too. Contributors can check out the project from our source repository and will find supplementary information in the guide to helping with Maven.
Examples
The following examples show how to use the Site Plugin in more advanced use cases:
- Creating Content
- Configuring the Site Descriptor
- Configuring Site Run
- Excluding Document Formats
Установка Maven.
1. Скачиваем последнюю версию .
2. Распаковываем архив в любую директорию.
3. Создаем переменную M2_HOME со значением «C:\apache-maven-2.2.1» или другой директорией с этой папкой.
4. Создаем переменную M2 со значением %M2_HOME%\bin.
5. Убеждаемся что есть переменная JAVA_HOME с путем к JDK (значение примерно такое «C:\program files\java\jdk1.6.0_10\«.
6. Изменяем переменную Path — дописываем в нее %M2%, чтобы папка с исполняемым файлом Maven была видна из командной строки.
7. Проверяем работу установленного Maven.
В командной строке вводим mvn -version
Должна появиться информация версиях Maven, JRE и ОС.
Maven создаст локальный репозиторий в личной папке пользователя — например C:\Users\username\.m2\repository.
Maven готов, можно создавать приложения.
Apache Maven Help Plugin
The Maven Help Plugin is used to get relative information about a project or the system. It can be used to get a description of a particular plugin, including the plugin’s goals with their parameters and component requirements, the effective POM and effective settings of the current build, and the profiles applied to the current project being built.
Goals Overview
The Help Plugin has 7 goals:
- help:active-profiles lists the profiles which are currently active for the build.
- help:all-profiles lists the available profiles under the current project.
- help:describe describes the attributes of a Plugin and/or a Mojo (Maven plain Old Java Object).
- help:effective-pom displays the effective POM as an XML for the current build, with the active profiles factored in. If verbose, a comment is added to each XML element describing the origin of the line.
- help:effective-settings displays the calculated settings as an XML for the project, given any profile enhancement and the inheritance of the global settings into the user-level settings.
- help:evaluate evaluates Maven expressions given by the user in an interactive mode.
- help:system displays a list of the platform details like system properties and environment variables.
Major Version Upgrade to version 3.0.0
Please note that the goal expressions has been completely removed from the plugin. All the Maven expressions that are supported as plugin parameters are available in the Javadoc of the PluginParameterExpressionEvaluator class.
Usage
General instructions on how to use the Help Plugin can be found on the usage page. Some more specific use cases are described in the examples given below. Last but not least, users occasionally contribute additional examples, tips or errata to the plugin’s wiki page.
If you feel like the plugin is missing a feature or has a defect, you can fill a feature request or bug report in our issue tracker. When creating a new issue, please provide a comprehensive description of your concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, entire debug logs, POMs or most preferably little demo projects attached to the issue are very much appreciated. Of course, patches are welcome, too. Contributors can check out the project from our source repository and will find supplementary information in the guide to helping with Maven.
Examples
To provide you with better understanding on some usages of the Help Plugin, you can take a look into the following example(s):
Configuring Describe Goal
Создание приложения из архетипа
На сайте http://maven.apache.org/guides/introduction/introduction-to-archetypes.html перечислены основные архетипы приложений, но несложно создать свой или найти более специфичный .
Для примера если нам нужно веб-приложение, находим подходящий архетип maven-archetype-webapp. В командной строке в нужном каталоге вводим команду Maven:
mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-webapp -DarchetypeArtifactId=maven-archetype-webapp
Теперь можем видеть наглядную структуру каталогов с говорящими названиями:
- java — тут будут классы
- webapp — страницы веб-приложения
- resources — ресурсы
- test — unit-тесты
Feature Summary
The following are the key features of Maven in a nutshell:
- Simple project setup that follows best practices — get a new project or module started in seconds
- Consistent usage across all projects — means no ramp up time for new developers coming onto a project
- Superior dependency management including automatic updating, dependency closures (also known as transitive dependencies)
- Able to easily work with multiple projects at the same time
- A large and growing repository of libraries and metadata to use out of the box, and arrangements in place with the largest Open Source projects for real-time availability of their latest releases
- Extensible, with the ability to easily write plugins in Java or scripting languages
- Instant access to new features with little or no extra configuration
- Ant tasks for dependency management and deployment outside of Maven
- Model based builds: Maven is able to build any number of projects into predefined output types such as a JAR, WAR, or distribution based on metadata about the project, without the need to do any scripting in most cases.
- Coherent site of project information: Using the same metadata as for the build process, Maven is able to generate a web site or PDF including any documentation you care to add, and adds to that standard reports about the state of development of the project. Examples of this information can be seen at the bottom of the left-hand navigation of this site under the «Project Information» and «Project Reports» submenus.
- Release management and distribution publication: Without much additional configuration, Maven will integrate with your source control system (such as Subversion or Git) and manage the release of a project based on a certain tag. It can also publish this to a distribution location for use by other projects. Maven is able to publish individual outputs such as a JAR, an archive including other dependencies and documentation, or as a source distribution.
- Dependency management: Maven encourages the use of a central repository of JARs and other dependencies. Maven comes with a mechanism that your project’s clients can use to download any JARs required for building your project from a central JAR repository much like Perl’s CPAN. This allows users of Maven to reuse JARs across projects and encourages communication between projects to ensure that backward compatibility issues are dealt with.
Apache Maven Deploy Plugin
The deploy plugin is primarily used during the deploy phase, to add your artifact(s) to a remote repository for sharing with other developers and projects. This is usually done in an integration or release environment. It can also be used to deploy a particular artifact (e.g. a third party jar like Sun’s non redistributable reference implementations).
As a repository contains more than the artifacts (POMs, the metadata, MD5 and SHA1 hash files…), deploying means not only copying the artifacts, but making sure all this information is correctly updated. It’s the reponsibility of the deploy plugin.
To work, the deployment will require:
- information about the repository: its location, the transport method used to access it (FTP, SCP, SFTP…) and the optional user specific required account information
- information about the artifact(s): the group, artifact, version, packaging, classifier…
- a deployer: a method to actually perform the deployment. This can be implemented as a wagon transport (making it cross-platform), or use a system specific method.
The information will be taken from the implied (or specified) pom and from the command line. The settings.xml file may also be parsed to retrieve user credentials.
Goals Overview
The deploy plugin has 2 goals:
- deploy:deploy is used to automatically install the artifact, its pom and the attached artifacts produced by a particular project. Most if not all of the information related to the deployment is stored in the project’s pom.
- deploy:deploy-file is used to install a single artifact along with its pom. In that case the artifact information can be taken from an optionally specified pomFile, but can be completed/overriden using the command line.
Major Version Upgrade to version 3.0.0
Please note that the following parameter has been completely removed from the plugin configuration:
uniqueVersion
As of Maven 3, snapshot artifacts will always be deployed using a timestamped version.
Usage
General instructions on how to use the Deploy Plugin can be found on the usage page. Some more specific use cases are described in the examples given below.
If you feel like the plugin is missing a feature or has a defect, you can fill a feature request or bug report in our issue tracker. When creating a new issue, please provide a comprehensive description of your concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, entire debug logs, POMs or most preferably little demo projects attached to the issue are very much appreciated. Of course, patches are welcome, too. Contributors can check out the project from our source repository and will find supplementary information in the guide to helping with Maven.
Examples
To provide you with better understanding on some usages of the deploy plugin, you can take a look into the following examples:
Project Deployment:
- Deployment with FTP
- Deployment with external SSH
File Deployment:
- Disable the generation of pom
- Deploy an artifact with a customed pom
- Deploy an artifact with classifier
- Disable timestamps suffix in an artifact
- Deploy an artifact in legacy layout
Сборка Java кода
Теперь все готово для сборки проекта Maven’ом. Вы можете выполнить несколько этапов жизненного цикла сборки,
включая компиляцию кода, создание библиотеки пакета(такого, как JAR-файл) и установку библиотеки в
локальный репозиторий Maven зависимостей.
Попробуйте собрать, выполнив команду, приведенную ниже:
Этим вы запустите Maven, передав ему указание на выполнение задачи compile. Когда он закончит,
вы должны найни скомпилированные .class файлы в target/classes директории.
Вряд ли вы захотите распостранять или работать напрямую с .class файлами, поэтому
вам полее подойдет выполнение задачи package:
Задача package включает компиляцию вашего Java кода, запуск тестов, а в конце упаковывает
в JAR-файл в target директории. Название JAR-файла будет основано на
и . К примеру, с минимальным pom.xml(см. выше), JAR-файл будет иметь
название gs-maven-initial-0.1.0.jar.
Если вы изменили значение с «jar» на «war», то результатом будет
WAR-файл в target директории вместо JAR-файла.
Maven также хранит репозиторий зависимостей на вашей локальной машине(обычно в .m2/repository
директории в вашей домашней папке) для быстрого доступа к зависимостям проекта. Если вы хотите
добавить JAR-файл вашего проекта в локальный репозиторий, тогда вам необходимо выполнить задачу :
Задача install включает компиляцию, тестирование, упаковку кода проекта, а затем
копирование в локальный репозиторий, тем самым другие проекты смогут ссылаться на него как на зависимость.
Говоря о зависимостях, пришло время объявлять зависимости в Maven сборке.
Описание Maven
Maven — один из самых популярных сборщиков для Java. Для чего его можно использовать:
- Сборка Java проекта с подтягиванием зависимостей.
- Создание jar.
- Автоматически сгенерировать сопроводительную документации для кода на основе комментариев.
- Создание дистрибутива.
Если проект java достаточно простой, можно собрать его вручную в командной строке. При больших объемах проекта такую команду записывают в bat/sh скрипт.
Структура проекта описывается через файл pom.xml (POM — Project Object Model), он должен лежать в корневой папке проекта.
Главным объектом Maven является артефакт (любая библиотека, хранящаяся в репозитории, зависимости и плагины).
Зависимости — это библиотеки, используемые в проекте для компиляции кода или его тестирования.
Плагины используются самим Maven при сборке проекта или других целей (деплоймент, создание файлов проекта для Eclipse и др.).
Архетип — стандартная организация файлов и каталогов, используемая в разных проектах (веб, swing-проекты, тесты). То есть Maven знает как обычно строятся проекты разных видов и в соответствии с выбранным архетипом создает структуру файлов и каталогов.
Название артефакта состоит из названия группы, собственного названия и версии. Например, Spring в среде Maven будет иметь название:
org.springframework.spring:2.5.5.
Последний домен — artifactId, все что перед ним — groupId.
Apache Maven PMD Plugin
The PMD Plugin allows you to automatically run the PMD code analysis tool on your project’s source code and generate a site report with its results. It also supports the separate Copy/Paste Detector tool (or CPD) distributed with PMD.
This version of Maven PMD Plugin uses PMD 6.29.0 and requires Java 7. See Upgrading PMD at Runtime for more information.
The plugin accepts configuration parameters that can be used to customize the execution of the PMD tool.
Goals Overview
This plugin has 4 goals:
- pmd:pmd creates a PMD site report based on the rulesets and configuration set in the plugin. It can also generate a pmd output file aside from the site report in any of the following formats: xml, csv or txt.
- pmd:cpd generates a report for PMD’s Copy/Paste Detector (CPD) tool. It can also generate a cpd results file in any of these formats: xml, csv or txt.
- pmd:check verifies that the PMD report is empty and fails the build if it is not. This goal is executed by default when pmd:pmd is executed.
- pmd:cpd-check verifies that the CPD report is empty and fails the build if it is not. This goal is executed by default when pmd:cpd is executed.
Usage
General instructions on how to use the PMD Plugin can be found on the usage page. Some more specific use cases are described in the examples given below.
If you feel like the plugin is missing a feature or has a defect, you can fill a feature request or bug report in our issue tracker. When creating a new issue, please provide a comprehensive description of your concern. Especially for fixing bugs it is crucial that the developers can reproduce your problem. For this reason, entire debug logs, POMs or most preferably little demo projects attached to the issue are very much appreciated. Of course, patches are welcome, too. Contributors can check out the project from our source repository and will find supplementary information in the guide to helping with Maven.
Upgrading Notes
Note: Starting with PMD 6.0.0 and Maven PMD Plugin 3.9.0, the rules have been reorganized into categories, e.g. /category/java/bestpractices.xml. So when upgrading to Maven PMD Plugin 3.9.0 you should review your plugin configuration and/or custom ruleset. See Using Rule Sets for more information.
Examples
To provide you with better understanding of some usages of the Maven PMD Plugin, you can take a look into the following examples:
- Upgrading PMD at Runtime
- Multimodule Configuration
- Remove Report
- Target JDK and Toolchains
- Using Rule Sets
- Violation Checking
- Analyzing JavaScript Code
- Analyzing Java Server Pages Code
- Finding duplicated code in C#
Overview
In this quick tutorial, we’ll show how to set the Java version in Maven.
Before moving on, we can check the default JDK version of Maven. Running the mvn -v command will show the Java version in which Maven runs.
2. Use the Compiler Plugin
We can specify the desired Java version in the compiler plugin.
2.1. Compiler Plugin
The first option is setting the version in compiler plugin properties:
The Maven compiler accepts this command with –target and –source versions. If we want to use the Java 8 language features, the –source should be set to 1.8.
Also, for the compiled classes to be compatible with JVM 1.8, the –target value should be 1.8.
The default value for both of them is the 1.6 version.
Alternatively, we can configure the compiler plugin directly:
The maven-compiler-plugin also has additional configuration properties that allow us to have more control over the compilation process beyond -source and -target versions.
2.2. Java 9 and Beyond
Furthermore, starting from the JDK 9 version, we can use a new -release command-line option. This new argument will automatically configure the compiler to produce class files that will link against the implementation of the given platform version.
By default, the -source and -target options don’t guarantee a cross-compilation.
This means that we cannot run our application on older versions of the platform. Additionally, to compile and run the programs for older Java versions, we also need to specify -bootclasspath option.
To cross-compile correctly, the new -release option replaces three flags: -source, -target and -bootclasspath.
After transforming our examples, we can declare the following for the plugin properties:
And for the maven-compiler-plugin starting from the 3.6 version, this is what we can write:
Notice that we can add the Java version in a new <release> attribute. In this example, we compile our application for Java 7.
What’s more, we don’t need a JDK 7 installed in our machine. Java 9 already contains all the information for linking the new language features with JDK 7.
3. Spring Boot Specification
Spring Boot applications specify the JDK version inside of the properties tags in the pom.xml file.
First, we need to add spring-boot-starter-parent as a parent to our project:
This parent POM allows us to configure default plugins and multiple properties including the Java version — by default, the Java version is 1.8.
However, we can override the default version of the parent by specifying the java.version property:
By setting the java.version property, we declare that the source and the target Java versions are both equal to 1.9.
Above all, we should keep in mind that this property is a Spring Boot Specification. Additionally, starting from Spring Boot 2.0, Java 8 is the minimum version.
This means we can’t use or configure Spring Boot for the older JDK versions.
4. Conclusion
This quick tutorial demonstrated the possible ways of setting Java version in our Maven project.
Here’s a summary of the main takeaways:
- Using <java.version> is possible only with the Spring Boot application.
- For simple cases, maven.compiler.source and maven.compiler.target properties should be the best fit.
- Finally, to have more control over the compilation process, use the maven-compiler-plugin configuration settings.