Spring boot starter parent что это
Из-за громоздкой конфигурации зависимостей настройка Spring для корпоративных приложений превратилась в весьма утомительное и подверженное ошибкам занятие. Особенно это относится к приложениям, которые используют также несколько сторонних библиотек.
Каждый раз, создавая очередное корпоративное Java-приложение на основе Spring, вам необходимо повторять одни и те же рутинные шаги по его настройке:
- В зависимости от типа создаваемого приложения (Spring MVC, Spring JDBC, Spring ORM и т. д.) импортировать необходимые Spring-модули
- Импортировать библиотеку web-контейнеров (в случае web-приложений)
- Импортировать необходимые сторонние библиотеки (например, Hibernate, Jackson), при этом вы должны искать версии, совместимые с указанной версией Spring
- Конфигурировать компоненты DAO, такие, как: источники данных, управление транзакциями и т. д.
- Конфигурировать компоненты web-слоя, такие, как: диспетчер ресурсов, view resolver
- Определить класс, который загрузит все необходимые конфигурации
1. Представляем Spring Boot
Авторы Spring решили предоставить разработчикам некоторые утилиты, которые автоматизируют процедуру настройки и ускоряют процесс создания и развертывания Spring-приложений, под общим названием Spring Boot.
Spring Boot — это полезный проект, целью которого является упрощение создания приложений на основе Spring. Он позволяет наиболее простым способом создать web-приложение, требуя от разработчиков минимум усилий по его настройке и написанию кода.
2. Особенности Spring Boot
Spring Boot обладает большим функционалом, но его наиболее значимыми особенностями являются: управление зависимостями, автоматическая конфигурация и встроенные контейнеры сервлетов.
2.1. Простота управления зависимостями
Чтобы ускорить процесс управления зависимостями, Spring Boot неявно упаковывает необходимые сторонние зависимости для каждого типа приложения на основе Spring и предоставляет их разработчику посредством так называемых starter-пакетов (spring-boot-starter-web, spring-boot-starter-data-jpa и т. д.).
Starter-пакеты представляют собой набор удобных дескрипторов зависимостей, которые можно включить в свое приложение. Это позволит получить универсальное решение для всех, связанных со Spring технологий, избавляя программиста от лишнего поиска примеров кода и загрузки из них требуемых дескрипторов зависимостей (пример таких дескрипторов и стартовых пакетов будет показан ниже).
Например, если вы хотите начать использовать Spring Data JPA для доступа к базе данных, просто включите в свой проект зависимость spring-boot-starter-data-jpa и все будет готово (вам не придется искать совместимые драйверы баз данных и библиотеки Hibernate).
Если вы хотите создать Spring web-приложение, просто добавьте зависимость spring-boot-starter-web, которая подтянет в проект все библиотеки, необходимые для разработки Spring MVC-приложений, таких как spring-webmvc, jackson-json, validation-api и Tomcat.
Другими словами, Spring Boot собирает все общие зависимости и определяет их в одном месте, что позволяет разработчикам просто использовать их, вместо того, чтобы изобретать колесо каждый раз, когда они создают новое приложение.
Следовательно, при использовании Spring Boot, файл pom.xml содержит намного меньше строк, чем при использовании его в Spring-приложениях.
Обратитесь к документации, чтобы ознакомиться со всеми Spring Boot starter-пакетами.

2.2. Автоматическая конфигурация
Второй превосходной возможностью Spring Boot является автоматическая конфигурация приложения.
После выбора подходящего starter-пакета, Spring Boot попытается автоматически настроить Spring-приложение на основе добавленных вами jar-зависимостей.
Например, если вы добавите Spring-boot-starter-web, Spring Boot автоматически сконфигурирует такие зарегистрированные бины, как DispatcherServlet, ResourceHandlers, MessageSource.
Если вы используете spring-boot-starter-jdbc, Spring Boot автоматически регистрирует бины DataSource, EntityManagerFactory, TransactionManager и считывает информацию для подключения к базе данных из файла application.properties.
Если вы не собираетесь использовать базу данных, и не предоставляете никаких подробных сведений о подключении в ручном режиме, Spring Boot автоматически настроит базу в памяти, без какой-либо дополнительной конфигурации с вашей стороны (при наличии H2 или HSQL библиотек).
Автоматическая конфигурация может быть полностью переопределена в любой момент с помощью пользовательских настроек.
2.3. Встроенная поддержка сервера приложений — контейнера сервлетов
Каждое Spring Boot web-приложение включает встроенный web-сервер. Посмотрите на список контейнеров сервлетов, которые поддерживаются «из коробки».
Разработчикам теперь не надо беспокоиться о настройке контейнера сервлетов и развертывании приложения на нем. Теперь приложение может запускаться само, как исполняемый jar-файл с использованием встроенного сервера.
Если вам нужно использовать отдельный HTTP-сервер, для этого достаточно исключить зависимости по умолчанию. Spring Boot предоставляет отдельные starter-пакеты для разных HTTP-серверов.
Создание автономных web-приложений со встроенными серверами не только удобно для разработки, но и является допустимым решением для приложений корпоративного уровня и становится все более полезно в мире микросервисов. Возможность быстро упаковать весь сервис (например, аутентификацию пользователя) в автономном и полностью развертываемом артефакте, который также предоставляет API — делает установку и развертывание приложения значительно проще.
Java Blog
В этом посте описывается, как разработать простое «Hello World!» веб-приложение, которое выделяет некоторые ключевые функции Spring Boot. Мы используем Maven для создания этого проекта, так как большинство IDE поддерживают его.
Вы можете сократить действия, описанные ниже, перейдя в start.spring.io и выбрав «Web» стартер из поисковика зависимостей. Это создает новую структуру проекта, так что вы можете сразу начать писать код.
Прежде чем мы начнем, откройте терминал и выполните следующие команды, чтобы убедиться, что у вас установлены валидные версии Java и Maven:
$ java -version java version "1.8.0_102" Java(TM) SE Runtime Environment (build 1.8.0_102-b14) Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode) $ mvn -v Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00) Maven home: /usr/local/Cellar/maven/3.3.9/libexec Java version: 1.8.0_102, vendor: Oracle Corporation
Этот пример должен быть создан в своей собственной папке. Последующие инструкции предполагают, что вы создали подходящую папку и это ваш текущий каталог.
Создание POM
Нам нужно начать с создания файла Maven pom.xml. pom.xml — это рецепт, который используется для создания вашего проекта. Откройте текстовый редактор и добавьте следующее:
4.0.0 com.example myproject 0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.2.4.RELEASE
Предыдущий список должен дать вам рабочую сборку. Вы можете проверить это, запустив mvn package (сейчас вы можете игнорировать предупреждение “jar will be empty — no content was marked for inclusion!” («jar будет пустым — содержимое не было помечено для включения!»)).
На этом этапе вы можете импортировать проект в IDE (большинство современных Java IDE включают встроенную поддержку Maven). Для простоты мы продолжаем использовать текстовый редактор для этого примера.
Добавление Classpath зависимостей
Spring Boot предоставляет несколько “Starters”, которые позволяют вам добавлять файлы jar в ваш путь к классам (classpath). Наше приложение использует spring-boot-starter-parent в родительском разделе POM. Spring-boot-starter-parent — это специальный стартер, который обеспечивает полезные значения по умолчанию Maven. Он также предоставляет раздел dependency-management (управления зависимостями), так что вы можете опустить теги version для общераспространенных зависимостей.
Другие «стартеры» предоставляют зависимости, которые вам могут понадобиться при разработке приложений определенного типа. Поскольку мы разрабатываем веб-приложение, мы добавляем зависимость spring-boot-starter-web. Перед этим мы можем посмотреть, что у нас есть, выполнив следующую команду:
$ mvn dependency:tree
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
Команда mvn dependency:tree печатает древовидное представление зависимостей вашего проекта. Вы можете видеть, что spring-boot-starter-parent сам по себе не предоставляет никаких зависимостей. Чтобы добавить необходимые зависимости, отредактируйте ваш pom.xml и добавьте зависимость spring-boot-starter-web непосредственно под parent разделом:
org.springframework.boot spring-boot-starter-web
Если вы снова запустите mvn dependency:tree, вы увидите, что теперь есть ряд дополнительных зависимостей, включая веб-сервер Tomcat и сам Spring Boot.
Пишем код
Чтобы закончить наше приложение, нам нужно создать один Java файл. По умолчанию Maven компилирует исходники из src/main/java, поэтому вам нужно создать структуру папок, а затем добавить файл с именем src/main/java/Example.java, содержащий следующий код:
import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.web.bind.annotation.*; @RestController @EnableAutoConfiguration public class Example < @RequestMapping("/") String home() < return "Hello World!"; >public static void main(String[] args) < SpringApplication.run(Example.class, args); >>
Хотя здесь не так много кода, довольно много происходит. Мы рассмотрим важные части в следующих нескольких разделах.
Аннотации @RestController и @RequestMapping
Первой аннотацией в нашем классе Example является @RestController. Это известно как аннотация стереотипа. Он предоставляет подсказки для людей, читающих код, и для Spring, что класс играет особую роль. В этом случае наш класс — это web @Controller, поэтому Spring учитывает его при обработке входящих веб-запросов.
Аннотация @RequestMapping предоставляет информацию о «маршрутизации». Он сообщает Spring, что любой HTTP-запрос с / путем должен быть сопоставлен с home методом. Аннотация @RestController сообщает Spring, чтобы визуализировать полученную строку непосредственно обратно в вызывающую программу.
Аннотации @RestController и @RequestMapping являются аннотациями Spring MVC (они не относятся к Spring Boot).
Аннотация @EnableAutoConfiguration
Вторая аннотация на уровне класса — @EnableAutoConfiguration. Эта аннотация говорит Spring Boot «угадать», как вы хотите сконфигурировать Spring, основываясь на зависимостях jar, которые вы добавили. Поскольку spring-boot-starter-web добавили Tomcat и Spring MVC, автоконфигурация предполагает, что вы разрабатываете веб-приложение, и соответствующим образом настраивает Spring.
Стартеры и автоконфигурация
Автоконфигурация рассчитана на то, чтобы хорошо работать со «Стартерами», но две концепции напрямую не связаны. Вы можете выбирать зависимости jar за пределами стартеров. Spring Boot по-прежнему делает все возможное, чтобы автоматически настроить приложение.
«main» метод
Заключительная часть нашего приложения является main методом. Это просто стандартный метод, который следует Java-соглашению для точки входа приложения. Наш main метод делегирует классу SpringApplication из Spring Boot, вызывая run. SpringApplication загружает наше приложение, запуская Spring, который, в свою очередь, запускает автоматически настроенный веб-сервер Tomcat. Нам нужно передать Example.class в качестве аргумента методу run, чтобы сообщить SpringApplication, который класс является основным компонентом Spring. Массив args также передается для предоставления любых аргументов командной строки.
Выполнение примера
На этом этапе ваше приложение должно работать. Поскольку вы использовали POM spring-boot-starter-parent, у вас есть метод run, который вы можете использовать для запуска приложения. Введите mvn spring-boot:run из корневого каталога проекта, чтобы запустить приложение. Вы должны увидеть вывод, похожий на следующий:
$ mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.2.4.RELEASE) . . . . . . . . (log output here) . . . . . Started Example in 2.222 seconds (JVM running for 6.514)
Если вы откроете веб-браузер для localhost:8080, вы должны увидеть следующее:
Hello World!
Чтобы выйти из приложения, нажмите Ctrl-C.
Создание исполняемого jar
Мы заканчиваем наш пример созданием полностью автономного исполняемого файла JAR, который мы можем запустить в продуктовой среде. Исполняемые jar (иногда называемые «fat jars») — это архивы, содержащие ваши скомпилированные классы вместе со всеми зависимостями jar, которые должен запускать ваш код.
Исполняемые jar и Java
Java не предоставляет стандартного способа загрузки вложенных файлов jar (файлов jar, которые сами содержатся внутри jar). Это может быть проблематично, если вы хотите распространять автономное приложение.
Чтобы решить эту проблему, многие разработчики используют «uber» jar. Uber jar упаковывает все классы из всех зависимостей приложения в один архив. Проблема с этим подходом состоит в том, что становится трудно увидеть, какие библиотеки находятся в вашем приложении. Это также может быть проблематично, если одно и то же имя файла (но с разным содержанием) используется в нескольких jar.
Spring Boot использует другой подход и позволяет напрямую вкладывать jar.
Чтобы создать исполняемый файл jar, нам нужно добавить плагин spring-boot-maven-plugin в наш pom.xml. Для этого вставьте следующие строки чуть ниже раздела dependencies:
org.springframework.boot spring-boot-maven-plugin
POM spring-boot-starter-parent включает конфигурацию для привязки repackage задачи. Если вы не используете parent POM, вам необходимо объявить эту конфигурацию самостоятельно. Подробности смотрите в документации к плагину.
Сохраните ваш pom.xml и запустите пакет mvn из командной строки следующим образом:
$ mvn package [INFO] Scanning for projects. [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building myproject 0.0.1-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] . .. [INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject --- [INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar [INFO] [INFO] --- spring-boot-maven-plugin:2.2.4.RELEASE:repackage (default) @ myproject --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------
Если вы посмотрите в целевой каталог, вы должны увидеть myproject-0.0.1-SNAPSHOT.jar. Размер файла должен быть около 10 МБ. Если вы хотите заглянуть внутрь, вы можете использовать jar tvf следующим образом:
$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar
Вы также должны увидеть гораздо меньший файл с именем myproject-0.0.1-SNAPSHOT.jar.original в целевом каталоге. Это оригинальный файл jar, созданный Maven до его повторной упаковки Spring Boot.
Чтобы запустить это приложение, используйте команду java -jar следующим образом:
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.2.4.RELEASE) . . . . . . . . (log output here) . . . . . Started Example in 2.536 seconds (JVM running for 2.864)
Как и прежде, для выхода из приложения нажмите ctrl-c.
- Spring Boot: особенности, системные требования
- Установка Spring Boot: Maven
- Установка Spring Boot: Gradle
Энтерпрайз головного мозга
Этим постом я хочу начать серию статей о Spring Boot, в которой расскажу и покажу на наглядных примерах, как разрабатывать приложения используя Spring Boot и Spring Framework. За год активного использования этого фреймворка накопилось немало опыта, информации и нетривиальных моментов, которые приходилось решать, что пора бы и поделиться этим всем.
Что такое Spring Boot?
Spring Boot — это фреймворк для быстрой разработки приложений на основе Spring Framework и его компонентов, входящих в Spring Data, Spring Security и другие подпроекты. Spring Boot предоставляет огромное количество сконфигурированных компонентов, что позволяет сократить время, затрачиваемое на конфигурирование приложения и состредоточиться непосредственно на разработке, а так же упрощает работу с зависимостями. Ну и конечно Spring Boot позволяет легко и просто разрабатывать bootiful-приложения (так разработчики Spring называют standalone-приложения, основанные на Spring Boot). Но это всё лишь поверхностно, на самом деле возможности Spring Boot значительно мощнее. В целом, Spring Boot является идеальным инструментом для разработки микросервисов.
О демонстрационном проекте
В рамках цикла статей я буду демонстрировать примеры использования Spring Boot на примере разработки достаточно простого, но в то же время наглядного веб-приложения — сервисдеска/хелпдеска.
Для проекта потребуется JDK 1.8, Maven и любая среда разработки (в моём случае — NetBeans).
Подготовка проекта
Создадим новый maven-проект с упаковкой в WAR. В нашем случае это обусловлено тем, что в рамках статей будет продемонстрировано использование JSP для построения представлений, а так же будет продемонстрировано развёртывание приложения в сервере приложений. Если вам этого не нужно, то с лихвой хватит и JAR-упаковки. В любом случае, и JAR, и WAR являются исполняемыми при использовании Spring Boot.
Первое, что нужно сделать — добавить управление зависимостями, предоставляемое Spring Boot.
Это можно сделать двумя способами:
1. Указать в качестве родительского проекта spring-boot-starter-parent, если у проекта нет родительского:
org.springframework.boot spring-boot-starter-parent 1.3.3.RELEASE
2. Указать dependencyManagement:
org.springframework.boot spring-boot-dependencies 1.3.3.RELEASE import pom
Это решит все возможные проблемы с версиями зависимостей, которые описаны в Spring Boot. Хоть этот шаг и необязателен, я рекомендую его проделывать при разработке приложений, так как разные стартеры одной версии Spring Boot могут ссылаться на разные версии одной и той же зависимости, что может привести к неожиданным и неочевидным ошибкам.
Второй шаг при подготовке проекта — указание maven-плагина, предоставляемого Spring Boot для сборки проекта:
1. При использовании родительского проекта:
org.springframework.boot spring-boot-maven-plugin
2. При использовании dependencyManagement:
org.springframework.boot spring-boot-maven-plugin repackage
Этот плагин найдёт класс, содержащий метод public static void main, пометит его главным и соберёт исполняемый JAR или WAR-файл, а так же скопирует в него все зависимости.
Ну и последний шаг, что бы получить работающее приложение — добавление в зависимости как минимум одного стартера (spring-boot-starter). В нашем случае понадобится spring-boot-starter-thymeleaf:
org.springframework.boot spring-boot-starter-thymeleaf
Spring Boot предоставляет большое количество стартеров практически на все случаи жизни. Стартер — это зависимость, содержащая все зависимости необходимые для реализации какой-либо функциональности в рамках разрабатывамого приложения. Так, например, что бы добавить приложению веб-функциональность, понадобится spring-boot-starter-web, который позволяет разрабатывать как стандартные веб-приложения, основанные на Spring WebMVC, так и REST-сервисы. Если же есть необходимость добавить приложению управление доступом, то можно добавить spring-boot-starter-security. Указанный мной стартер spring-boot-starter-thymeleaf содержит все зависимости, необходимые для разработки веб-приложения с использованием Thymeleaf в качестве фреймворка для построения представлений.
Теперь у нас всё готово для непосредственной разработки приложения на Spring Boot.
Разработка приложения
Самый простой пример — отображение представления в браузере без использования контроллера.
Первым делом создадим, класс, с которого будет начинаться работа нашего приложения:
package name.alexkosarev.bootdesk; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; @SpringBootApplication public class Application extends SpringBootServletInitializer < public static void main(String[] args) < SpringApplication.run(Application.class, args) .registerShutdownHook(); >@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) < return builder.sources(Application.class); >>
- Аннтоация @SpringBootApplication объединяет аннотации @Configuration, @EnableAutoConfiguration и @ComponentScan, объявляет Application классом-конфигурацией, включает автоматическую конфигурацию приложения и включает автоматический поиск компонентов в пакете name.alexkosarev.bootdesk и во всех вложенных.
- SpringApplication.run(Application.class, args) запускает приложение при запуске при помощи java -jar
- Класс Application расширяет класс SpringBootServletInitializer и переопределяет метод SpringApplicationBuilder configure(SpringApplicationBuilder builder) для запуска приложения при развёртывании в сервере приложении.
package name.alexkosarev.bootdesk.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebConfig extends WebMvcConfigurerAdapter < @Override public void addViewControllers(ViewControllerRegistry registry) < registry.addRedirectViewController("/", "/site/index"); registry.addViewController("/site/index") .setViewName("site/index"); >>
- Добавить в файл свойств application.properties, расположенном в ресурсах проекта, строку spring.thymeleaf.mode=LEGACYHTML5
- Добавить в зависимости проекта nekohtml из группы nekohtml:
nekohtml nekohtml 1.9.6.2
На данном этапе приложение имеет минимальную функциональность и готово к первому запуску.
Сборка и запуск приложения
Для начала соберём приложение стандартным способом: командой mvn package или при помощи IDE. В директории target окажется два варианта WAR-архива: bootiful, с именем файла, заканчивающимся на .war, и обычный, заканчивающийся на .war.orginal. Обычный WAR-файл не является исполняемым, не содержит provided-зависимости, но может быть развёрнут в сервере приложений. Bootiful-вариант содержит все необходимые для работы зависимости, не может быть развёрнут в сервере приложений (попытка развернуть его в сервере приложений приведёт к ошибке), но может быть запущен как самостоятельное приложение при помощи команды java -jar bootdesk-1.0.0.war.
Кстати, если вы разрабатываете приложение на основе Spring Boot с упаковкой в JAR, то после сборки получите так же два варианта: bootiful, содержащий все необходимые для работы зависимости, и обычный вариант, зависимости для запуска которого нужно будет указывать при помощи -classpath.
Запустив приложение при помощи команды java -jar bootdesk-1.0.0.war мы увидим вывод нашего приложения.
Если мы откроем адрес http://localhost:8080, приложение сначала нас перенаправит на http://localhost:8080/site/index, а затем покажет нам содержимое index.html:

Spring Boot и JSP
По умолчанию ни один стартер из предоставляемых Spring Boot не предоставляет возможности работать с JSP. Но это решается достаточно просто:
1. В зависимости проекта нужно добавить tomcat-embed-jasper и jstl:
org.apache.tomcat.embed tomcat-embed-jasper provided jstl jstl 1.2
Обратите внимание на scope=provided для tomcat-embed-jasper.
2. В WebConfig сконфигурировать ViewResolver:
@Bean public ViewResolver viewResolver() < UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver(); urlBasedViewResolver.setViewClass(JstlView.class); urlBasedViewResolver.setPrefix("/WEB-INF/templates/"); urlBasedViewResolver.setSuffix(".jspx"); return urlBasedViewResolver; >
После этого можно будет использовать JSP-представления, а так же использовать Apache Tiles, если в этом будет необходимость.
В следующем посте я добавлю приложению немного функцональности, добавив взаимодействие с базой данных посредством Spring Data JPA. Так же я постараюсь в ближайшие несколько дней выложить проект в GitHub и опубликую видеоподкаст.
Spring Boot Maven Plugin Documentation
The Spring Boot Maven Plugin provides Spring Boot support in Apache Maven. It allows you to package executable jar or war archives, run Spring Boot applications, generate build information and start your Spring Boot application prior to running integration tests.
2. Getting Started
To use the Spring Boot Maven Plugin, include the appropriate XML in the plugins section of your pom.xml , as shown in the following example:
4.0.0 getting-started org.springframework.boot spring-boot-maven-plugin
If you use a milestone or snapshot release, you also need to add the appropriate pluginRepository elements, as shown in the following listing:
spring-snapshots https://repo.spring.io/snapshot spring-milestones https://repo.spring.io/milestone
3. Using the Plugin
Maven users can inherit from the spring-boot-starter-parent project to obtain sensible defaults. The parent project provides the following features:
- Java 17 as the default compiler level.
- UTF-8 source encoding.
- Compilation with -parameters .
- A dependency management section, inherited from the spring-boot-dependencies POM, that manages the versions of common dependencies. This dependency management lets you omit tags for those dependencies when used in your own POM.
- An execution of the repackage goal with a repackage execution id.
- A native profile that configures the build to be able to generate a Native image.
- Sensible resource filtering.
- Sensible plugin configuration (Git commit ID, and shade).
- Sensible resource filtering for application.properties and application.yml including profile-specific files (for example, application-dev.properties and application-dev.yml )
| Since the application.properties and application.yml files accept Spring style placeholders ( $ ), the Maven filtering is changed to use @..@ placeholders. (You can override that by setting a Maven property called resource.delimiter .) |
3.1. Inheriting the Starter Parent POM
To configure your project to inherit from the spring-boot-starter-parent , set the parent as follows:
org.springframework.boot spring-boot-starter-parent 3.1.5
| You should need to specify only the Spring Boot version number on this dependency. If you import additional starters, you can safely omit the version number. |
With that setup, you can also override individual dependencies by overriding a property in your own project. For instance, to use a different version of the SLF4J library and the Spring Data release train, you would add the following to your pom.xml :
1.7.30 Moore-SR6
Browse the Dependency versions Appendix in the Spring Boot reference for a complete list of dependency version properties.
3.2. Using Spring Boot without the Parent POM
There may be reasons for you not to inherit from the spring-boot-starter-parent POM. You may have your own corporate standard parent that you need to use or you may prefer to explicitly declare all your Maven configuration.
If you do not want to use the spring-boot-starter-parent , you can still keep the benefit of the dependency management (but not the plugin management) by using an import scoped dependency, as follows:
org.springframework.boot spring-boot-dependencies 3.1.5 pom import
The preceding sample setup does not let you override individual dependencies by using properties, as explained above. To achieve the same result, you need to add entries in the dependencyManagement section of your project before the spring-boot-dependencies entry. For instance, to use a different version of the SLF4J library and the Spring Data release train, you could add the following elements to your pom.xml :
org.slf4j slf4j-api 1.7.30 org.springframework.data spring-data-releasetrain 2020.0.0-SR1 pom import org.springframework.boot spring-boot-dependencies 3.1.5 pom import
3.3. Overriding settings on the command-line
The plugin offers a number of user properties, starting with spring-boot , to let you customize the configuration from the command-line.
For instance, you could tune the profiles to enable when running the application as follows:
$ mvn spring-boot:run -Dspring-boot.run.profiles=dev,local
If you want to both have a default while allowing it to be overridden on the command-line, you should use a combination of a user-provided project property and MOJO configuration.
local,dev org.springframework.boot spring-boot-maven-plugin $
The above makes sure that local and dev are enabled by default. Now a dedicated property has been exposed, this can be overridden on the command-line as well:
$ mvn spring-boot:run -Dapp.profiles=test
4. Goals
The Spring Boot Plugin has the following goals:
Package an application into an OCI image using a buildpack, forking the lifecycle to make sure that package ran. This goal is suitable for command-line invocation. If you need to configure a goal execution in your build, use build-image-no-fork instead.
Package an application into an OCI image using a buildpack, but without forking the lifecycle. This goal should be used when configuring a goal execution in your build. To invoke the goal on the command-line, use build-image instead.
Generate a build-info.properties file based on the content of the current MavenProject .
Display help information on spring-boot-maven-plugin. Call mvn spring-boot:help -Ddetail=true -Dgoal= to display parameter details.
Invoke the AOT engine on the application.
Invoke the AOT engine on tests.
Repackage existing JAR and WAR archives so that they can be executed from the command line using java -jar . With layout=NONE can also be used simply to package a JAR with nested dependencies (and no main class, so not executable).
Run an application in place.
Start a spring application. Contrary to the run goal, this does not block and allows other goals to operate on the application. This goal is typically used in integration test scenario where the application is started before a test suite and stopped after.
Stop an application that has been started by the «start» goal. Typically invoked once a test suite has completed.
Run an application in place using the test runtime classpath. The main class that will be used to launch the application is determined as follows: The configured main class, if any. Then the main class found in the test classes directory, if any. Then the main class found in the classes directory, if any.
5. Packaging Executable Archives
The plugin can create executable archives (jar files and war files) that contain all of an application’s dependencies and can then be run with java -jar .
Packaging an executable archive is performed by the repackage goal, as shown in the following example:
org.springframework.boot spring-boot-maven-plugin repackage
| If you are using spring-boot-starter-parent , such execution is already pre-configured with a repackage execution ID so that only the plugin definition should be added. |
The example above repackages a jar or war archive that is built during the package phase of the Maven lifecycle, including any provided dependencies that are defined in the project. If some of these dependencies need to be excluded, you can use one of the exclude options; see the dependency exclusion for more details.
The original (that is non-executable) artifact is renamed to .original by default but it is also possible to keep the original artifact using a custom classifier.
| The outputFileNameMapping feature of the maven-war-plugin is currently not supported. |
The spring-boot-devtools and spring-boot-docker-compose modules are automatically excluded by default (you can control this using the excludeDevtools and excludeDockerCompose properties). In order to make that work with war packaging, the spring-boot-devtools and spring-boot-docker-compose dependencies must be set as optional or with the provided scope.
The plugin rewrites your manifest, and in particular it manages the Main-Class and Start-Class entries. If the defaults don’t work you have to configure the values in the Spring Boot plugin, not in the jar plugin. The Main-Class in the manifest is controlled by the layout property of the Spring Boot plugin, as shown in the following example:
org.springframework.boot spring-boot-maven-plugin $ ZIP repackage
The layout property defaults to a value determined by the archive type ( jar or war ). The following layouts are available:
- JAR : regular executable JAR layout.
- WAR : executable WAR layout. provided dependencies are placed in WEB-INF/lib-provided to avoid any clash when the war is deployed in a servlet container.
- ZIP (alias to DIR ): similar to the JAR layout using PropertiesLauncher .
- NONE : Bundle all dependencies and project resources. Does not bundle a bootstrap loader.
5.1. Layered Jar or War
A repackaged jar contains the application’s classes and dependencies in BOOT-INF/classes and BOOT-INF/lib respectively. Similarly, an executable war contains the application’s classes in WEB-INF/classes and dependencies in WEB-INF/lib and WEB-INF/lib-provided . For cases where a docker image needs to be built from the contents of a jar or war, it’s useful to be able to separate these directories further so that they can be written into distinct layers.
Layered archives use the same layout as a regular repackaged jar or war, but include an additional meta-data file that describes each layer.
By default, the following layers are defined:
- dependencies for any dependency whose version does not contain SNAPSHOT .
- spring-boot-loader for the loader classes.
- snapshot-dependencies for any dependency whose version contains SNAPSHOT .
- application for local module dependencies, application classes, and resources.
Module dependencies are identified by looking at all of the modules that are part of the current build. If a module dependency can only be resolved because it has been installed into Maven’s local cache and it is not part of the current build, it will be identified as regular dependency.
The layers order is important as it determines how likely previous layers can be cached when part of the application changes. The default order is dependencies , spring-boot-loader , snapshot-dependencies , application . Content that is least likely to change should be added first, followed by layers that are more likely to change.
The repackaged archive includes the layers.idx file by default. To disable this feature, you can do so in the following manner:
org.springframework.boot spring-boot-maven-plugin false
5.1.1. Custom Layers Configuration
Depending on your application, you may want to tune how layers are created and add new ones. This can be done using a separate configuration file that should be registered as shown below:
org.springframework.boot spring-boot-maven-plugin true $/src/layers.xml
The configuration file describes how an archive can be separated into layers, and the order of those layers. The following example shows how the default ordering described above can be defined explicitly:
org/springframework/boot/loader/** *:*:*SNAPSHOT dependencies spring-boot-loader snapshot-dependencies application
The layers XML format is defined in three sections:
- The block defines how the application classes and resources should be layered.
- The block defines how dependencies should be layered.
- The block defines the order that the layers should be written.
Nested blocks are used within and sections to claim content for a layer. The blocks are evaluated in the order that they are defined, from top to bottom. Any content not claimed by an earlier block remains available for subsequent blocks to consider.
The block claims content using nested and elements. The section uses Ant-style path matching for include/exclude expressions. The section uses group:artifact[:version] patterns. It also provides and elements that can be used to include or exclude local module dependencies.
If no is defined, then all content (not claimed by an earlier block) is considered.
If no is defined, then no exclusions are applied.
Looking at the example above, we can see that the first will claim all module dependencies for the application.layer . The next will claim all SNAPSHOT dependencies for the snapshot-dependencies layer. The final will claim anything left (in this case, any dependency that is not a SNAPSHOT) for the dependencies layer.
The block has similar rules. First claiming org/springframework/boot/loader/** content for the spring-boot-loader layer. Then claiming any remaining classes and resources for the application layer.
| The order that blocks are defined is often different from the order that the layers are written. For this reason the element must always be included and must cover all layers referenced by the blocks. |
5.2. spring-boot:repackage
Repackage existing JAR and WAR archives so that they can be executed from the command line using java -jar . With layout=NONE can also be used simply to package a JAR with nested dependencies (and no main class, so not executable).
5.2.1. Required parameters
5.2.2. Optional parameters
5.2.3. Parameter details
attach
Attach the repackaged archive to be installed into your local Maven repository or deployed to a remote repository. If no classifier has been configured, it will replace the normal jar. If a classifier has been configured such that the normal jar and the repackaged jar are different, it will be attached alongside the normal jar. When the property is set to false , the repackaged archive will not be installed or deployed.
classifier
Classifier to add to the repackaged archive. If not given, the main artifact will be replaced by the repackaged archive. If given, the classifier will also be used to determine the source archive to repackage: if an artifact with that classifier already exists, it will be used as source and replaced. If no such artifact exists, the main artifact will be used as source and the repackaged archive will be attached as a supplemental artifact with that classifier. Attaching the artifact allows to deploy it alongside to the original one, see the Maven documentation for more details.
embeddedLaunchScript
The embedded launch script to prepend to the front of the jar if it is fully executable. If not specified the ‘Spring Boot’ default script will be used.
embeddedLaunchScriptProperties
Properties that should be expanded in the embedded launch script.
excludeDevtools
Exclude Spring Boot devtools from the repackaged archive.
excludeDockerCompose
Exclude Spring Boot dev services from the repackaged archive.
excludeGroupIds
Comma separated list of groupId names to exclude (exact match).
excludes
Collection of artifact definitions to exclude. The Exclude element defines mandatory groupId and artifactId properties and an optional classifier property.
executable
Make a fully executable jar for *nix machines by prepending a launch script to the jar.
Currently, some tools do not accept this format so you may not always be able to use this technique. For example, jar -xf may silently fail to extract a jar or war that has been made fully-executable. It is recommended that you only enable this option if you intend to execute it directly, rather than running it with java -jar or deploying it to a servlet container.
includeSystemScope
Include system scoped dependencies.
includes
Collection of artifact definitions to include. The Include element defines mandatory groupId and artifactId properties and an optional mandatory groupId and artifactId properties and an optional classifier property.
layers
Layer configuration with options to disable layer creation, exclude layer tools jar, and provide a custom layers configuration file.
layout
The type of archive (which corresponds to how the dependencies are laid out inside it). Possible values are JAR , WAR , ZIP , DIR , NONE . Defaults to a guess based on the archive type.
layoutFactory
The layout factory that will be used to create the executable archive if no explicit layout is set. Alternative layouts implementations can be provided by 3rd parties.
mainClass
The name of the main class. If not specified the first compiled class found that contains a main method will be used.
outputDirectory
Directory containing the generated archive.
outputTimestamp
Timestamp for reproducible output archive entries, either formatted as ISO 8601 ( yyyy-MM-dd’T’HH:mm:ssXXX ) or an int representing seconds since the epoch.
requiresUnpack
A list of the libraries that must be unpacked from fat jars in order to run. Specify each library as a with a and a and they will be unpacked at runtime.
skip
Skip the execution.
5.3. Examples
5.3.1. Custom Classifier
By default, the repackage goal replaces the original artifact with the repackaged one. That is a sane behavior for modules that represent an application but if your module is used as a dependency of another module, you need to provide a classifier for the repackaged one. The reason for that is that application classes are packaged in BOOT-INF/classes so that the dependent module cannot load a repackaged jar’s classes.
If that is the case or if you prefer to keep the original artifact and attach the repackaged one with a different classifier, configure the plugin as shown in the following example:
org.springframework.boot spring-boot-maven-plugin repackage repackage exec
If you are using spring-boot-starter-parent , the repackage goal is executed automatically in an execution with id repackage . In that setup, only the configuration should be specified, as shown in the following example:
org.springframework.boot spring-boot-maven-plugin repackage exec
This configuration will generate two artifacts: the original one and the repackaged counter part produced by the repackage goal. Both will be installed/deployed transparently.
You can also use the same configuration if you want to repackage a secondary artifact the same way the main artifact is replaced. The following configuration installs/deploys a single task classified artifact with the repackaged application:
org.apache.maven.plugins maven-jar-plugin jar package task org.springframework.boot spring-boot-maven-plugin repackage repackage task
As both the maven-jar-plugin and the spring-boot-maven-plugin runs at the same phase, it is important that the jar plugin is defined first (so that it runs before the repackage goal). Again, if you are using spring-boot-starter-parent , this can be simplified as follows:
org.apache.maven.plugins maven-jar-plugin default-jar task org.springframework.boot spring-boot-maven-plugin repackage task
5.3.2. Custom Name
If you need the repackaged jar to have a different local name than the one defined by the artifactId attribute of the project, use the standard finalName , as shown in the following example:
my-app org.springframework.boot spring-boot-maven-plugin repackage repackage
This configuration will generate the repackaged artifact in target/my-app.jar .
5.3.3. Local Repackaged Artifact
By default, the repackage goal replaces the original artifact with the executable one. If you need to only deploy the original jar and yet be able to run your app with the regular file name, configure the plugin as follows:
org.springframework.boot spring-boot-maven-plugin repackage repackage false
This configuration generates two artifacts: the original one and the executable counter part produced by the repackage goal. Only the original one will be installed/deployed.
5.3.4. Custom Layout
Spring Boot repackages the jar file for this project using a custom layout factory defined in the additional jar file, provided as a dependency to the build plugin:
org.springframework.boot spring-boot-maven-plugin repackage repackage value com.example custom-layout 0.0.1.BUILD-SNAPSHOT
The layout factory is provided as an implementation of LayoutFactory (from spring-boot-loader-tools ) explicitly specified in the pom. If there is only one custom LayoutFactory on the plugin classpath and it is listed in META-INF/spring.factories then it is unnecessary to explicitly set it in the plugin configuration.
Layout factories are always ignored if an explicit layout is set.
5.3.5. Dependency Exclusion
By default, both the repackage and the run goals will include any provided dependencies that are defined in the project. A Spring Boot project should consider provided dependencies as «container» dependencies that are required to run the application. Generally speaking, Spring Boot projects are not used as dependencies and are therefore unlikely to have any optional dependencies. When a project does have optional dependencies they too will be included by the repackage and run goals.
Some of these dependencies may not be required at all and should be excluded from the executable jar. For consistency, they should not be present either when running the application.
There are two ways one can exclude a dependency from being packaged/used at runtime:
- Exclude a specific artifact identified by groupId and artifactId , optionally with a classifier if needed.
- Exclude any artifact belonging to a given groupId .
The following example excludes com.example:module1 , and only that artifact:
org.springframework.boot spring-boot-maven-plugin com.example module1
This example excludes any artifact belonging to the com.example group:
org.springframework.boot spring-boot-maven-plugin com.example
5.3.6. Layered Archive Tools
When a layered jar or war is created, the spring-boot-jarmode-layertools jar will be added as a dependency to your archive. With this jar on the classpath, you can launch your application in a special mode which allows the bootstrap code to run something entirely different from your application, for example, something that extracts the layers. If you wish to exclude this dependency, you can do so in the following manner:
org.springframework.boot spring-boot-maven-plugin false
5.3.7. Custom Layers Configuration
The default setup splits dependencies into snapshot and non-snapshot, however, you may have more complex rules. For example, you may want to isolate company-specific dependencies of your project in a dedicated layer. The following layers.xml configuration shown one such setup:
org/springframework/boot/loader/** *:*:*SNAPSHOT com.acme:* dependencies spring-boot-loader snapshot-dependencies company-dependencies application
The configuration above creates an additional company-dependencies layer with all libraries with the com.acme groupId.
6. Packaging OCI Images
The plugin can create an OCI image from a jar or war file using Cloud Native Buildpacks (CNB). Images can be built on the command-line using the build-image goal. This makes sure that the package lifecycle has run before the image is created.
| For security reasons, images build and run as non-root users. See the CNB specification for more details. |
The easiest way to get started is to invoke mvn spring-boot:build-image on a project. It is possible to automate the creation of an image whenever the package phase is invoked, as shown in the following example:
org.springframework.boot spring-boot-maven-plugin build-image-no-fork
| Use build-image-no-fork when binding the goal to the package lifecycle. This goal is similar to build-image but does not fork the lifecycle to make sure package has run. In the rest of this section, build-image is used to refer to either the build-image or build-image-no-fork goals. |
| While the buildpack runs from an executable archive, it is not necessary to execute the repackage goal first as the executable archive is created automatically if necessary. When the build-image repackages the application, it applies the same settings as the repackage goal would, that is dependencies can be excluded using one of the exclude options. The spring-boot-devtools and spring-boot-docker-compose modules are automatically excluded by default (you can control this using the excludeDevtools and excludeDockerCompose properties). |
6.1. Docker Daemon
The build-image goal requires access to a Docker daemon. By default, it will communicate with a Docker daemon over a local connection. This works with Docker Engine on all supported platforms without configuration.
Environment variables can be set to configure the build-image goal to use an alternative local or remote connection. The following table shows the environment variables and their values:
URL containing the host and port for the Docker daemon — for example tcp://192.168.99.100:2376
Enable secure HTTPS protocol when set to 1 (optional)
Path to certificate and key files for HTTPS (required if DOCKER_TLS_VERIFY=1 , ignored otherwise)
Docker daemon connection information can also be provided using docker parameters in the plugin configuration. The following table summarizes the available parameters:
URL containing the host and port for the Docker daemon — for example tcp://192.168.99.100:2376
Enable secure HTTPS protocol when set to true (optional)
Path to certificate and key files for HTTPS (required if tlsVerify is true , ignored otherwise)
When true , the value of the host property will be provided to the container that is created for the CNB builder (optional)
For more details, see also examples.
6.2. Docker Registry
If the Docker images specified by the builder or runImage parameters are stored in a private Docker image registry that requires authentication, the authentication credentials can be provided using docker.builderRegistry parameters.
If the generated Docker image is to be published to a Docker image registry, the authentication credentials can be provided using docker.publishRegistry parameters.
Parameters are provided for user authentication or identity token authentication. Consult the documentation for the Docker registry being used to store images for further information on supported authentication methods.
The following table summarizes the available parameters for docker.builderRegistry and docker.publishRegistry :
Username for the Docker image registry user. Required for user authentication.
Password for the Docker image registry user. Required for user authentication.
Address of the Docker image registry. Optional for user authentication.
E-mail address for the Docker image registry user. Optional for user authentication.
Identity token for the Docker image registry user. Required for token authentication.
For more details, see also examples.
6.3. Image Customizations
The plugin invokes a builder to orchestrate the generation of an image. The builder includes multiple buildpacks that can inspect the application to influence the generated image. By default, the plugin chooses a builder image. The name of the generated image is deduced from project properties.
The image parameter allows configuration of the builder and how it should operate on the project. The following table summarizes the available parameters and their default values:
Name of the Builder image to use.
Name of the run image to use.
No default value, indicating the run image specified in Builder metadata should be used.
Image name for the generated image.
Policy used to determine when to pull the builder and run images from the registry. Acceptable values are ALWAYS , NEVER , and IF_NOT_PRESENT .
Environment variables that should be passed to the builder.
Buildpacks that the builder should use when building the image. Only the specified buildpacks will be used, overriding the default buildpacks included in the builder. Buildpack references must be in one of the following forms:
- Buildpack in the builder — [urn:cnb:builder:][@]
- Buildpack in a directory on the file system — [file://]
- Buildpack in a gzipped tar (.tgz) file on the file system — [file://]/
- Buildpack in an OCI image — [docker://]/[:][@]
None, indicating the builder should use the buildpacks included in it.
Volume bind mounts that should be mounted to the builder container when building the image. The bindings will be passed unparsed and unvalidated to Docker when creating the builder container. Bindings must be in one of the following forms:
Where can contain:
- ro to mount the volume as read-only in the container
- rw to mount the volume as readable and writable in the container
- volume-opt=key=value to specify key-value pairs consisting of an option name and its value
The network driver the builder container will be configured to use. The value supplied will be passed unvalidated to Docker when creating the builder container.
Whether to clean the cache before building.
Enables verbose logging of builder operations.
Whether to publish the generated image to a Docker registry.
One or more additional tags to apply to the generated image. The values provided to the tags option should be full image references in the form of [image name]:[tag] or [repository]/[image name]:[tag] .
A cache containing layers created by buildpacks and used by the image building process.
A named volume in the Docker daemon, with a name derived from the image name.
A cache containing layers created by buildpacks and used by the image launching process.
A named volume in the Docker daemon, with a name derived from the image name.
A date that will be used to set the Created field in the generated image’s metadata. The value must be a string in the ISO 8601 instant format, or now to use the current date and time.
A fixed date that enables build reproducibility.
The path to a directory that application contents will be uploaded to in the builder image. Application contents will also be in this location in the generated image.
| The plugin detects the target Java compatibility of the project using the compiler’s plugin configuration or the maven.compiler.target property. When using the default Paketo builder and buildpacks, the plugin instructs the buildpacks to install the same Java version. You can override this behaviour as shown in the builder configuration examples. |
For more details, see also examples.
6.4. spring-boot:build-image
Package an application into an OCI image using a buildpack, forking the lifecycle to make sure that package ran. This goal is suitable for command-line invocation. If you need to configure a goal execution in your build, use build-image-no-fork instead.
6.4.1. Required parameters
6.4.2. Optional parameters
6.4.3. Parameter details
classifier
Classifier used when finding the source archive.
docker
Docker configuration options.
excludeDevtools
Exclude Spring Boot devtools from the repackaged archive.
excludeDockerCompose
Exclude Spring Boot dev services from the repackaged archive.
excludeGroupIds
Comma separated list of groupId names to exclude (exact match).
excludes
Collection of artifact definitions to exclude. The Exclude element defines mandatory groupId and artifactId properties and an optional classifier property.
image
Image configuration, with builder , runImage , name , env , cleanCache , verboseLogging , pullPolicy , and publish options.
includeSystemScope
Include system scoped dependencies.
includes
Collection of artifact definitions to include. The Include element defines mandatory groupId and artifactId properties and an optional mandatory groupId and artifactId properties and an optional classifier property.
layers
Layer configuration with options to disable layer creation, exclude layer tools jar, and provide a custom layers configuration file.
layout
The type of archive (which corresponds to how the dependencies are laid out inside it). Possible values are JAR , WAR , ZIP , DIR , NONE . Defaults to a guess based on the archive type.
layoutFactory
The layout factory that will be used to create the executable archive if no explicit layout is set. Alternative layouts implementations can be provided by 3rd parties.
mainClass
The name of the main class. If not specified the first compiled class found that contains a main method will be used.
skip
Skip the execution.
sourceDirectory
Directory containing the source archive.
6.5. spring-boot:build-image-no-fork
Package an application into an OCI image using a buildpack, but without forking the lifecycle. This goal should be used when configuring a goal execution in your build. To invoke the goal on the command-line, use build-image instead.
6.5.1. Required parameters
6.5.2. Optional parameters
6.5.3. Parameter details
classifier
Classifier used when finding the source archive.
docker
Docker configuration options.
excludeDevtools
Exclude Spring Boot devtools from the repackaged archive.
excludeDockerCompose
Exclude Spring Boot dev services from the repackaged archive.
excludeGroupIds
Comma separated list of groupId names to exclude (exact match).
excludes
Collection of artifact definitions to exclude. The Exclude element defines mandatory groupId and artifactId properties and an optional classifier property.
image
Image configuration, with builder , runImage , name , env , cleanCache , verboseLogging , pullPolicy , and publish options.
includeSystemScope
Include system scoped dependencies.
includes
Collection of artifact definitions to include. The Include element defines mandatory groupId and artifactId properties and an optional mandatory groupId and artifactId properties and an optional classifier property.
layers
Layer configuration with options to disable layer creation, exclude layer tools jar, and provide a custom layers configuration file.
layout
The type of archive (which corresponds to how the dependencies are laid out inside it). Possible values are JAR , WAR , ZIP , DIR , NONE . Defaults to a guess based on the archive type.
layoutFactory
The layout factory that will be used to create the executable archive if no explicit layout is set. Alternative layouts implementations can be provided by 3rd parties.
mainClass
The name of the main class. If not specified the first compiled class found that contains a main method will be used.
skip
Skip the execution.
sourceDirectory
Directory containing the source archive.
6.6. Examples
6.6.1. Custom Image Builder
If you need to customize the builder used to create the image or the run image used to launch the built image, configure the plugin as shown in the following example:
org.springframework.boot spring-boot-maven-plugin mine/java-cnb-builder mine/java-cnb-run
This configuration will use a builder image with the name mine/java-cnb-builder and the tag latest , and the run image named mine/java-cnb-run and the tag latest .
The builder and run image can be specified on the command line as well, as shown in this example:
$ mvn spring-boot:build-image -Dspring-boot.build-image.builder=mine/java-cnb-builder -Dspring-boot.build-image.runImage=mine/java-cnb-run
6.6.2. Builder Configuration
If the builder exposes configuration options using environment variables, those can be set using the env attributes.
The following is an example of configuring the JVM version used by the Paketo Java buildpacks at build time:
org.springframework.boot spring-boot-maven-plugin 17
If there is a network proxy between the Docker daemon the builder runs in and network locations that buildpacks download artifacts from, you will need to configure the builder to use the proxy. When using the Paketo builder, this can be accomplished by setting the HTTPS_PROXY and/or HTTP_PROXY environment variables as show in the following example:
org.springframework.boot spring-boot-maven-plugin http://proxy.example.com https://proxy.example.com
6.6.3. Runtime JVM Configuration
Paketo Java buildpacks configure the JVM runtime environment by setting the JAVA_TOOL_OPTIONS environment variable. The buildpack-provided JAVA_TOOL_OPTIONS value can be modified to customize JVM runtime behavior when the application image is launched in a container.
Environment variable modifications that should be stored in the image and applied to every deployment can be set as described in the Paketo documentation and shown in the following example:
org.springframework.boot spring-boot-maven-plugin -XX:+HeapDumpOnOutOfMemoryError
6.6.4. Custom Image Name
By default, the image name is inferred from the artifactId and the version of the project, something like docker.io/library/$:$ . You can take control over the name, as shown in the following example:
org.springframework.boot spring-boot-maven-plugin example.com/library/$
| This configuration does not provide an explicit tag so latest is used. It is possible to specify a tag as well, either using $ , any property available in the build or a hardcoded version. |
The image name can be specified on the command line as well, as shown in this example:
$ mvn spring-boot:build-image -Dspring-boot.build-image.imageName=example.com/library/my-app:v1
6.6.5. Buildpacks
By default, the builder will use buildpacks included in the builder image and apply them in a pre-defined order. An alternative set of buildpacks can be provided to apply buildpacks that are not included in the builder, or to change the order of included buildpacks. When one or more buildpacks are provided, only the specified buildpacks will be applied.
The following example instructs the builder to use a custom buildpack packaged in a .tgz file, followed by a buildpack included in the builder.
org.springframework.boot spring-boot-maven-plugin file:///path/to/example-buildpack.tgz urn:cnb:builder:paketo-buildpacks/java
Buildpacks can be specified in any of the forms shown below.
A buildpack located in a CNB Builder (version may be omitted if there is only one buildpack in the builder matching the buildpack-id ):
- urn:cnb:builder:buildpack-id
- urn:cnb:builder:[email protected]
- buildpack-id
- [email protected]
A path to a directory containing buildpack content (not supported on Windows):
- file:///path/to/buildpack/
- /path/to/buildpack/
A path to a gzipped tar file containing buildpack content:
- file:///path/to/buildpack.tgz
- /path/to/buildpack.tgz
An OCI image containing a packaged buildpack:
- docker://example/buildpack
- docker:///example/buildpack:latest
- docker:///example/buildpack@sha256:45b23dee08…
- example/buildpack
- example/buildpack:latest
- example/buildpack@sha256:45b23dee08…
6.6.6. Image Publishing
The generated image can be published to a Docker registry by enabling a publish option.
If the Docker registry requires authentication, the credentials can be configured using docker.publishRegistry parameters. If the Docker registry does not require authentication, the docker.publishRegistry configuration can be omitted.
| The registry that the image will be published to is determined by the registry part of the image name ( docker.example.com in these examples). If docker.publishRegistry credentials are configured and include a url parameter, this value is passed to the registry but is not used to determine the publishing registry location. |
org.springframework.boot spring-boot-maven-plugin docker.example.com/library/$ true user secret
The publish option can be specified on the command line as well, as shown in this example:
$ mvn spring-boot:build-image -Dspring-boot.build-image.imageName=docker.example.com/library/my-app:v1 -Dspring-boot.build-image.publish=true
When using the publish option on the command line with authentication, you can provide credentials using properties as in this example:
$ mvn spring-boot:build-image \ -Ddocker.publishRegistry.username=user \ -Ddocker.publishRegistry.password=secret \ -Ddocker.publishRegistry.url=docker.example.com \ -Dspring-boot.build-image.publish=true \ -Dspring-boot.build-image.imageName=docker.example.com/library/my-app:v1
and reference the properties in the XML configuration:
org.springframework.boot spring-boot-maven-plugin $ $ $
6.6.7. Builder Cache Configuration
The CNB builder caches layers that are used when building and launching an image. By default, these caches are stored as named volumes in the Docker daemon with names that are derived from the full name of the target image. If the image name changes frequently, for example when the project version is used as a tag in the image name, then the caches can be invalidated frequently.
The cache volumes can be configured to use alternative names to give more control over cache lifecycle as shown in the following example:
org.springframework.boot spring-boot-maven-plugin cache-$.build cache-$.launch
6.6.8. Docker Configuration
Docker Configuration for minikube
The plugin can communicate with the Docker daemon provided by minikube instead of the default local connection.
On Linux and macOS, environment variables can be set using the command eval $(minikube docker-env) after minikube has been started.
The plugin can also be configured to use the minikube daemon by providing connection details similar to those shown in the following example:
org.springframework.boot spring-boot-maven-plugin tcp://192.168.99.100:2376 true /home/user/.minikube/certs
Docker Configuration for podman
The plugin can communicate with a podman container engine.
The plugin can be configured to use podman local connection by providing connection details similar to those shown in the following example:
org.springframework.boot spring-boot-maven-plugin unix:///run/user/1000/podman/podman.sock true
| With the podman CLI installed, the command podman info —format=’>’ can be used to get the value for the docker.host configuration property shown in this example. |
Docker Configuration for Authentication
If the builder or run image are stored in a private Docker registry that supports user authentication, authentication details can be provided using docker.builderRegistry parameters as shown in the following example:
If the builder or run image is stored in a private Docker registry that supports token authentication, the token value can be provided using docker.builderRegistry parameters as shown in the following example:
org.springframework.boot spring-boot-maven-plugin 9cbaf023786cd7.
7. Running your Application with Maven
The plugin includes a run goal which can be used to launch your application from the command line, as shown in the following example:
$ mvn spring-boot:run
Application arguments can be specified using the arguments parameter, see using application arguments for more details.
The application is executed in a forked process and setting properties on the command-line will not affect the application. If you need to specify some JVM arguments (that is for debugging purposes), you can use the jvmArguments parameter, see Debug the application for more details. There is also explicit support for system properties and environment variables.
As enabling a profile is quite common, there is dedicated profiles property that offers a shortcut for -Dspring-boot.run.jvmArguments=»-Dspring.profiles.active=dev» , see Specify active profiles.
Spring Boot devtools is a module to improve the development-time experience when working on Spring Boot applications. To enable it, just add the following dependency to your project:
org.springframework.boot spring-boot-devtools true
When devtools is running, it detects change when you recompile your application and automatically refreshes it. This works for not only resources but code as well. It also provides a LiveReload server so that it can automatically trigger a browser refresh whenever things change.
Devtools can also be configured to only refresh the browser whenever a static resource has changed (and ignore any change in the code). Just include the following property in your project:
spring.devtools.remote.restart.enabled=false
Prior to devtools , the plugin supported hot refreshing of resources by default which has now be disabled in favour of the solution described above. You can restore it at any time by configuring your project:
org.springframework.boot spring-boot-maven-plugin true
When addResources is enabled, any src/main/resources directory will be added to the application classpath when you run the application and any duplicate found in the classes output will be removed. This allows hot refreshing of resources which can be very useful when developing web applications. For example, you can work on HTML, CSS or JavaScript files and see your changes immediately without recompiling your application. It is also a helpful way of allowing your front end developers to work without needing to download and install a Java IDE.
| A side effect of using this feature is that filtering of resources at build time will not work. |
In order to be consistent with the repackage goal, the run goal builds the classpath in such a way that any dependency that is excluded in the plugin’s configuration gets excluded from the classpath as well. For more details, see the dedicated example.
Sometimes it is useful to run a test variant of your application. For example, if you want to use Testcontainers at development time or make use of some test stubs. Use the test-run goal with many of the same features and configuration options as run for this purpose.
7.1. spring-boot:run
Run an application in place.