Java spring boot что это
Перейти к содержимому

Java spring boot что это

  • автор:

Введение в Spring Boot: создание простого REST API на Java

Из-за громоздкой конфигурации зависимостей настройка 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 — делает установку и развертывание приложения значительно проще

3. Требования к установке Spring Boot

Для настройки и запуска Spring Boot приложений требуется следующее:

  • Java 8+
  • Apache Maven 3.x

4. Создание Spring Boot приложения

Теперь давайте перейдем к практике и реализуем очень простой REST API для приема платежей, используя возможности Spring Boot

4.1. Создание web-проекта с использованием Maven

Создайте Maven-проект в используемой вами IDE, назвав его SpringBootRestService

Обязательно используйте версию Java 8+, поскольку Spring Boot не работает с более ранними версиями

4.2. Конфигурация pom.xml

Вторым шагом необходимо настроить Spring Boot в файле pom.xml

Все приложения Spring Boot конфигурируются от spring-boot-starter-parent, поэтому перед дальнейшим определением зависимостей, добавьте starter-parent следующим образом:

Т.к. мы создаем REST API, то необходимо в качестве зависимости использовать spring-boot-starter-web, которая неявно определяет все остальные зависимости, такие как spring-core, spring-web, spring-webmvc, servlet api, и библиотеку jackson-databind, поэтому просто добавьте в pom.xml следующее:

Теперь следующие jar-библиотеки автоматически импортируются в ваш проект:

image

Следующий шаг — добавляем Spring Boot плагин:

Последний шаг — сделать так, чтобы Maven генерировал исполняемый jar-файл при сборке:

Ниже приведен полный файл pom.xml:

Как видите, используя одну зависимость, мы можем создать полностью функциональное web-приложение

4.3. Создание ресурсов REST

Теперь мы собираемся создать контроллер платежей вместе с POJO-классами для запросов и ответов

Напишем класс запроса платежа:

А также класс, обрабатывающий базовый ответ, возвращаемый нашим сервисом:

А теперь создадим контроллер:

4.4. Создание основного класса приложения

Этот последний шаг заключается в создании класса конфигурации и запуска приложения. Spring Boot поддерживает новую аннотацию @SpringBootApplication, которая эквивалентна использованию @Configuration, @EnableAutoConfiguration и @ComponentScan с их атрибутами по умолчанию

Таким образом, вам просто нужно создать класс, аннотированный с помощью @SpringBootApplication, а Spring Boot включит автоматическую настройку и отсканирует ваши ресурсы в текущем пакете:

5. Развертывание приложения Spring Boot

Теперь давайте воспользуемся третьей замечательной особенностью Spring Boot — это встроенный сервер. Все, что нам нужно сделать — это создать исполняемый jar-файл с помощью Maven и запустить его, как обычное автономное приложение:

  • Войдите в режим командной строки (команда cmd), перейдите в папку с pom.xml и введите команду mvn clean package
  • Maven cгенерирует исполняемый jar-файл с именем SpringBootRestService-1.0.jar
  • Перейдите в папку cd target
  • Затем запустите jar-файл: java -jar SpringBootRestService-1.0.jar
  • Перейдите в браузере по адресу http://localhost:8080/payment

Наш REST API запущен и готов обслуживать запросы через порт 8080 (по умолчанию)

В этой статье мы рассмотрели возможности Spring Boot и создали полностью рабочий пример с использованием встроенного сервера

В переводе обновили информацию:
  • Spring-boot-starter-parent изменили версию с 1.5.8.RELEASE на 2.1.1.RELEASE и соответственно был обновлен список библиотек, которые подтягивает Maven
  • Убрали объявления репозиториев Spring, зависимости подтягиваются из центрального репозитория
  • В классе BaseResponse поля сделали final, добавили конструктор и убрали сеттеры
  • В контроллере PaymentController ввели метод showStatus() с @GetMapping для тестирования приложения в браузере
  • Заменили @RequestMapping в методах на @GetMapping/@PostMapping
  • Также были внесены правки по развертыванию приложения с командной строки

UPDATE:

Как заметил Lure_of_Chaos, теперь уже все можно сделать автоматически через SPRING INITIALIZR. Причем не выходя из любимой JetBrains IntelliJ IDEA.

Introducing Spring Boot

Spring Boot helps you to create stand-alone, production-grade Spring-based applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

You can use Spring Boot to create Java applications that can be started by using java -jar or more traditional war deployments.

Our primary goals are:

Provide a radically faster and widely accessible getting-started experience for all Spring development.

Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.

Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).

Absolutely no code generation (when not targeting native image) and no requirement for XML configuration.

Spring Boot 3.1.0

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can «just run».

We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need minimal Spring configuration.

If you’re looking for information about a specific version, or instructions about how to upgrade from an earlier release, check out the project release notes section on our wiki.

Features

Create stand-alone Spring applications

Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

Provide opinionated ‘starter’ dependencies to simplify your build configuration

Automatically configure Spring and 3rd party libraries whenever possible

Provide production-ready features such as metrics, health checks, and externalized configuration

Absolutely no code generation and no requirement for XML configuration

Getting Started

Super quick — try the Quickstart Guide.

Or search through all our guides on the Guides homepage.

Talks and videos

Quickstart Your Project

Bootstrap your application with Spring Initializr.

Get ahead

VMware offers training and certification to turbo-charge your progress.

Get support

Spring Runtime offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Name already in use

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.adoc

Spring Boot helps you to create Spring-powered, production-grade applications and services with absolute minimum fuss. It takes an opinionated view of the Spring platform so that new and existing users can quickly get to the bits they need.

You can use Spring Boot to create stand-alone Java applications that can be started using java -jar or more traditional WAR deployments. We also provide a command-line tool that runs Spring scripts.

Our primary goals are:

Provide a radically faster and widely accessible getting started experience for all Spring development.

Be opinionated, but get out of the way quickly as requirements start to diverge from the defaults.

Provide a range of non-functional features common to large classes of projects (for example, embedded servers, security, metrics, health checks, externalized configuration).

Absolutely no code generation and no requirement for XML configuration.

Installation and Getting Started

The reference documentation includes detailed installation instructions as well as a comprehensive getting started guide.

Here is a quick teaser of a complete Spring Boot application in Java:

Are you having trouble with Spring Boot? We want to help!

Check the reference documentation, especially the How-to’s — they provide solutions to the most common questions.

Learn the Spring basics — Spring Boot builds on many other Spring projects; check the spring.io website for a wealth of reference documentation. If you are new to Spring, try one of the guides.

If you are upgrading, read the release notes for upgrade instructions and «new and noteworthy» features.

Ask a question — we monitor stackoverflow.com for questions tagged with spring-boot . You can also chat with the community on Gitter.

Spring Boot uses GitHub’s integrated issue tracking system to record bugs and feature requests. If you want to raise an issue, please follow the recommendations below:

Before you log a bug, please search the issue tracker to see if someone has already reported the problem.

If the issue doesn’t already exist, create a new issue.

Please provide as much information as possible with the issue report. We like to know the Spring Boot version, operating system, and JVM version you’re using.

If you need to paste code or include a stack trace, use Markdown. «` escapes before and after your text.

If possible, try to create a test case or project that replicates the problem and attach it to the issue.

Building from Source

You don’t need to build from source to use Spring Boot (binaries in repo.spring.io), but if you want to try out the latest and greatest, Spring Boot can be built and published to your local Maven cache using the Gradle wrapper. You also need JDK 17.

This will build all of the jars and documentation and publish them to your local Maven cache. It won’t run any of the tests. If you want to build everything, use the build task:

There are several modules in Spring Boot. Here is a quick overview:

The main library providing features that support the other parts of Spring Boot. These include:

The SpringApplication class, providing static convenience methods that can be used to write a stand-alone Spring Application. Its sole job is to create and refresh an appropriate Spring ApplicationContext .

Embedded web applications with a choice of container (Tomcat, Jetty, or Undertow).

First-class externalized configuration support.

Convenience ApplicationContext initializers, including support for sensible logging defaults.

Spring Boot can configure large parts of typical applications based on the content of their classpath. A single @EnableAutoConfiguration annotation triggers auto-configuration of the Spring context.

Auto-configuration attempts to deduce which beans a user might need. For example, if HSQLDB is on the classpath, and the user has not configured any database connections, then they probably want an in-memory database to be defined. Auto-configuration will always back away as the user starts to define their own beans.

Starters are a set of convenient dependency descriptors that you can include in your application. You get a one-stop shop for all the Spring and related technology you need without having to hunt through sample code and copy-paste loads of dependency descriptors. For example, if you want to get started using Spring and JPA for database access, include the spring-boot-starter-data-jpa dependency in your project, and you are good to go.

Actuator endpoints let you monitor and interact with your application. Spring Boot Actuator provides the infrastructure required for actuator endpoints. It contains annotation support for actuator endpoints. This module provides many endpoints, including the HealthEndpoint , EnvironmentEndpoint , BeansEndpoint , and many more.

This provides auto-configuration for actuator endpoints based on the content of the classpath and a set of properties. For instance, if Micrometer is on the classpath, it will auto-configure the MetricsEndpoint . It contains configuration to expose endpoints over HTTP or JMX. Just like Spring Boot AutoConfigure, this will back away as the user starts to define their own beans.

This module contains core items and annotations that can be helpful when testing your application.

Like other Spring Boot auto-configuration modules, spring-boot-test-autoconfigure provides auto-configuration for tests based on the classpath. It includes many annotations that can automatically configure a slice of your application that needs to be tested.

Spring Boot Loader provides the secret sauce that allows you to build a single jar file that can be launched using java -jar . Generally, you will not need to use spring-boot-loader directly but work with the Gradle or Maven plugin instead.

The spring-boot-devtools module provides additional development-time features, such as automatic restarts, for a smoother application development experience. Developer tools are automatically disabled when running a fully packaged application.

The spring.io site contains several guides that show how to use Spring Boot step-by-step:

Building an Application with Spring Boot is an introductory guide that shows you how to create an application, run it, and add some management services.

Building a RESTful Web Service with Spring Boot Actuator is a guide to creating a REST web service and also shows how the server can be configured.

Converting a Spring Boot JAR Application to a WAR shows you how to run applications in a web server as a WAR file.

Spring Boot is Open Source software released under the Apache 2.0 license.

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

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