Реактивное программирование со Spring Boot 2. Часть 2
Spring Blog
Spring Boot 2.2.0
On behalf of the Spring Boot team and everyone that has contributed, I am delighted to announce that Spring Boot 2.2.0 has been released and is available now from repo.spring.io, Maven Central and Bintray. This release adds a significant number of new features and improvements. For full upgrade instructions and new and noteworthy features please see the release notes.
What’s new in 2.2
Dependency upgrades
Spring Boot 2.2 moves to new versions of several Spring projects:
- Spring AMQP 2.2
- Spring Batch 4.2
- Spring Data Moore
- Spring Framework 5.2
- Spring HATEOAS 1.0
- Spring Integration 5.2
- Spring Kafka 2.3
- Spring Security 5.2
- Spring Session Corn
We’ve also upgraded to the latest stable releases of other third-party libraries wherever possible. Some of the more notable third-party dependency upgrades in this release include:
- Elasticsearch 6.7
- Flyway 6.0
- Jackson 2.10
- JUnit 5.5
- Micrometer 1.3
- Reactor Dysprosium
- Solr 8.0
Performance improvements
As part of our ongoing efforts to improve performance, we’ve made some significant progress in Spring Boot 2.2 on top of those made in 2.1. Applications will now start even faster and consume less memory while they do so. This can be particularly beneficial in environments with very tight memory constraints.
Lazy initialization
It is now possible to enable global lazy initialization to reduce startup time via the spring.main.lazy-initialization property. Please note that using this feature does come at a cost:
- Handling of HTTP requests may take longer while any deferred initialisation occurs
- Failures that would normally occur at startup will now not occur until later
Please see this blog post for a broader discussion of the new feature and some guidance on when it should and should not be enabled.
Java 13 support
Following on from Spring Framework 5.2’s support for Java 13, Spring Boot 2.2 now also supports Java 13 while also remaining compatible with Java 11 and 8.
Immutable @ConfigurationProperties binding
Configuration properties now support constructor-based binding, which allows a @ConfigurationProperties -annotated class to be immutable. Constructor-based binding can be enabled by annotating a @ConfigurationProperties class or one of its constructors with @ConstructorBinding . Annotations such as @DefaultValue and @DateTimeFormat can be used on constructor parameters that are provided by configuration property binding.
Please see the relevant section of the reference documentation for further details.
RSocket Support
Extensive auto-configuration has been added for RSocket along with a new starter, spring-boot-starter-rsocket . Spring Security’s RSocket integration is also auto-configured when the spring-security-rsocket is on the classpath. Please see the relevant section of the reference documentation for further details.
Health indicator groups
It is now possible to organize health indicators into groups. A typical example, if you deploy your application to Kubernetes, is that you may want different groups of health indicators for your “liveness” and “readiness” probes.
Groups can be configured via configuration properties. The following creates a custom group with only the DataSource indicator:
The custom group can be invoked by hitting localhost:8080/actuator/health/custom. Check the updated reference documentation for more details.
Other changes
There’s a whole host of other changes and improvements that are documented in the release notes. You can also find a list of deprecated classes and methods that we plan to remove in the next version.
Thank you
We want to take this opportunity to again thank all our users and contributors. We’ve now had over 600 people submit code, and there have been over 23000 commits to the project.
Spring WebFlux Tutorial
By Lokesh Gupta | Filed Under: Spring WebFlux
The reactive-stack web framework, Spring WebFlux, has been added Spring 5.0. It is fully non-blocking, supports reactive streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers. In this spring webflux tutorial, we will learn the basic concepts behind reactive programming, webflux apis and a fully functional hello world example.
1. Reactive Programming
Reactive programming is a programming paradigm that promotes an asynchronous, non-blocking, event-driven approach to data processing. Reactive programming involves modeling data and events as observable data streams and implementing data processing routines to react to the changes in those streams.
Before digging deeper into reactive world, first understand the difference between blocking vs non-blocking request processing.
1.1. Blocking vs non-blocking (async) request processing
1.1.1. Blocking request processing
In traditional MVC applications, when a request come to server, a servlet thread is created. It delegates the request to worker threads for I/O operations such as database access etc. During the time worker threads are busy, servlet thread (request thread) remain in waiting status and thus it is blocked. It is also called synchronous request processing.
Blocking request processing
As server can have some finite number of request threads, it limits the server capability to process that number of requests at maximum server load. It may hamper the performance and limit the full utilization of server capability.
1.1.2. Non-blocking request processing
In non-blocking or asynchronous request processing, no thread is in waiting state. There is generally only one request thread receiving the request.
All incoming requests come with a event handler and call back information. Request thread delegates the incoming requests to a thread pool (generally small number of threads) which delegate the request to it’s handler function and immediately start processing other incoming requests from request thread.
When the handler function is complete, one of thread from pool collect the response and pass it to the call back function.
Non-blocking request processing
Non-blocking nature of threads helps in scaling the performance of the application. Small number of threads means less memory utilization and also less context switching as well.
1.2. What is reactive programming?
The term, “reactive,” refers to programming models that are built around reacting to changes. It is build around publisher-subscriber pattern (observer pattern). In reactive style of programming, we make a request for resource and start performing other things. When the data is available, we get the notification along with data inform of call back function. In callback function, we handle the response as per application/user needs.
One important thing to remember is back pressure. In non-blocking code, it becomes important to control the rate of events so that a fast producer does not overwhelm its destination.
Reactive web programming is great for applications that have streaming data, and clients that consume it and stream it to their users. It is not great for developing traditional CRUD applications. If you’re developing the next Facebook or Twitter with lots of data, a reactive API might be just what you’re looking for.
2. Reactive Streams API
The new Reactive Streams API was created by engineers from Netflix, Pivotal, Lightbend, RedHat, Twitter, and Oracle, among others and is now part of Java 9. It defines four interfaces:
- Publisher: Emits a sequence of events to subscribers according to the demand received from its subscribers. A publisher can serve multiple subscribers.
It has a single method:
Subscriber: Receives and processes events emitted by a Publisher. Please note that no notifications will be received until Subscription#request(long) is called to signal the demand.
It has four methods to handle various kind of responses received.
Two popular implementations of reactive streams are RxJava (https://github.com/ReactiveX/RxJava) and Project Reactor (https://projectreactor.io/).
3. What is Spring WebFlux ?
Spring WebFlux is parallel version of Spring MVC and supports fully non-blocking reactive streams. It support the back pressure concept and uses Netty as inbuilt server to run reactive applications. If you are familiar with Spring MVC programming style, you can easily work on webflux also.
Spring webflux uses project reactor as reactive library. Reactor is a Reactive Streams library and, therefore, all of its operators support non-blocking back pressure. It is developed in close collaboration with Spring.
Spring WebFlux heavily uses two publishers :
- Mono: Returns 0 or 1 element.
- Flux: Returns 0…N elements. A Flux can be endless, meaning that it can keep emitting elements forever. Also it can return a sequence of elements and then send a completion notification when it has returned all of its elements.
In Spring WebFlux, we call reactive APIs/functions that return monos and fluxes and your controllers will return monos and fluxes. When you invoke an API that returns a mono or a flux, it will return immediately. The results of the function call will be delivered to you through the mono or flux when they become available.
To build a truly non-blocking application, we must aim to create/use all of its components as non-blocking i.e. client, controller, middle services and even the database. If one of them is blocking the requests, our aim will be defeated.
4. Spring Boot WebFlux Example
In this Spring boot 2 application, I am creating employee management system. I chosen it because, while learning, you can compare it with traditional MVC style application. To make it fully non-blocking, I am using mongodb as back-end database.
4.1. Maven dependencies
Include spring-boot-starter-webflux , spring-boot-starter-data-mongodb-reactive , spring-boot-starter-test and reactor-test dependencies.
4.2. Configurations
Webflux Configuration
MongoDb Configuration
Application Configuration
Properties file
Logging configuration
Spring boot application
4.3. REST Controller
4.4. Service classes
4.5. DAO repository
4.6. Model
5. Demo
Start the application and check requests and responses.

Notice that I am testing the API with Postman chrome browser extension which is a blocking client. It will display the result only when It has collected the response for both employees.
To verify the non-blocking response feature, hit the URL in the chrome browser directly. The results will appear one by one, as and when they are available in form of events (text/event-stream). To better view the result, consider adding a delay to controller API.
Spring WebFlux Demo – Event Stream
6. Spring WebFlux Tutorial – Conclusion
Both Spring MVC and Spring WebFlux support client-server architecture but there is a key difference in the concurrency model and the default behavior for blocking nature and threads. In Spring MVC, it is assumed that applications can block the current thread while in webflux, threads are non-blocking by default. It is the main difference between spring webflux vs mvc.
Reactive and non-blocking generally do not make applications run faster. The expected benefit of reactive and non-blocking is the ability to scale the application with a small, fixed number of threads and lesser memory requirements. It makes applications more resilient under load because they scale in a more predictable manner.
Drop me your questions related to this spring boot webflux tutorial.
Spring WebFlux Tutorial
By Lokesh Gupta | Filed Under: Spring WebFlux
The reactive-stack web framework, Spring WebFlux, has been added Spring 5.0. It is fully non-blocking, supports reactive streams back pressure, and runs on such servers as Netty, Undertow, and Servlet 3.1+ containers. In this spring webflux tutorial, we will learn the basic concepts behind reactive programming, webflux apis and a fully functional hello world example.
1. Reactive Programming
Reactive programming is a programming paradigm that promotes an asynchronous, non-blocking, event-driven approach to data processing. Reactive programming involves modeling data and events as observable data streams and implementing data processing routines to react to the changes in those streams.
Before digging deeper into reactive world, first understand the difference between blocking vs non-blocking request processing.
1.1. Blocking vs non-blocking (async) request processing
1.1.1. Blocking request processing
In traditional MVC applications, when a request come to server, a servlet thread is created. It delegates the request to worker threads for I/O operations such as database access etc. During the time worker threads are busy, servlet thread (request thread) remain in waiting status and thus it is blocked. It is also called synchronous request processing.
Blocking request processing
As server can have some finite number of request threads, it limits the server capability to process that number of requests at maximum server load. It may hamper the performance and limit the full utilization of server capability.
1.1.2. Non-blocking request processing
In non-blocking or asynchronous request processing, no thread is in waiting state. There is generally only one request thread receiving the request.
All incoming requests come with a event handler and call back information. Request thread delegates the incoming requests to a thread pool (generally small number of threads) which delegate the request to it’s handler function and immediately start processing other incoming requests from request thread.
When the handler function is complete, one of thread from pool collect the response and pass it to the call back function.
Non-blocking request processing
Non-blocking nature of threads helps in scaling the performance of the application. Small number of threads means less memory utilization and also less context switching as well.
1.2. What is reactive programming?
The term, “reactive,” refers to programming models that are built around reacting to changes. It is build around publisher-subscriber pattern (observer pattern). In reactive style of programming, we make a request for resource and start performing other things. When the data is available, we get the notification along with data inform of call back function. In callback function, we handle the response as per application/user needs.
One important thing to remember is back pressure. In non-blocking code, it becomes important to control the rate of events so that a fast producer does not overwhelm its destination.
Reactive web programming is great for applications that have streaming data, and clients that consume it and stream it to their users. It is not great for developing traditional CRUD applications. If you’re developing the next Facebook or Twitter with lots of data, a reactive API might be just what you’re looking for.
2. Reactive Streams API
The new Reactive Streams API was created by engineers from Netflix, Pivotal, Lightbend, RedHat, Twitter, and Oracle, among others and is now part of Java 9. It defines four interfaces:
- Publisher: Emits a sequence of events to subscribers according to the demand received from its subscribers. A publisher can serve multiple subscribers.
It has a single method:
Subscriber: Receives and processes events emitted by a Publisher. Please note that no notifications will be received until Subscription#request(long) is called to signal the demand.
It has four methods to handle various kind of responses received.
Two popular implementations of reactive streams are RxJava (https://github.com/ReactiveX/RxJava) and Project Reactor (https://projectreactor.io/).
3. What is Spring WebFlux ?
Spring WebFlux is parallel version of Spring MVC and supports fully non-blocking reactive streams. It support the back pressure concept and uses Netty as inbuilt server to run reactive applications. If you are familiar with Spring MVC programming style, you can easily work on webflux also.
Spring webflux uses project reactor as reactive library. Reactor is a Reactive Streams library and, therefore, all of its operators support non-blocking back pressure. It is developed in close collaboration with Spring.
Spring WebFlux heavily uses two publishers :
- Mono: Returns 0 or 1 element.
- Flux: Returns 0…N elements. A Flux can be endless, meaning that it can keep emitting elements forever. Also it can return a sequence of elements and then send a completion notification when it has returned all of its elements.
In Spring WebFlux, we call reactive APIs/functions that return monos and fluxes and your controllers will return monos and fluxes. When you invoke an API that returns a mono or a flux, it will return immediately. The results of the function call will be delivered to you through the mono or flux when they become available.
To build a truly non-blocking application, we must aim to create/use all of its components as non-blocking i.e. client, controller, middle services and even the database. If one of them is blocking the requests, our aim will be defeated.
4. Spring Boot WebFlux Example
In this Spring boot 2 application, I am creating employee management system. I chosen it because, while learning, you can compare it with traditional MVC style application. To make it fully non-blocking, I am using mongodb as back-end database.
4.1. Maven dependencies
Include spring-boot-starter-webflux , spring-boot-starter-data-mongodb-reactive , spring-boot-starter-test and reactor-test dependencies.
4.2. Configurations
Webflux Configuration
MongoDb Configuration
Application Configuration
Properties file
Logging configuration
Spring boot application
4.3. REST Controller
4.4. Service classes
4.5. DAO repository
4.6. Model
5. Demo
Start the application and check requests and responses.

Notice that I am testing the API with Postman chrome browser extension which is a blocking client. It will display the result only when It has collected the response for both employees.
To verify the non-blocking response feature, hit the URL in the chrome browser directly. The results will appear one by one, as and when they are available in form of events (text/event-stream). To better view the result, consider adding a delay to controller API.
Spring WebFlux Demo – Event Stream
6. Spring WebFlux Tutorial – Conclusion
Both Spring MVC and Spring WebFlux support client-server architecture but there is a key difference in the concurrency model and the default behavior for blocking nature and threads. In Spring MVC, it is assumed that applications can block the current thread while in webflux, threads are non-blocking by default. It is the main difference between spring webflux vs mvc.
Reactive and non-blocking generally do not make applications run faster. The expected benefit of reactive and non-blocking is the ability to scale the application with a small, fixed number of threads and lesser memory requirements. It makes applications more resilient under load because they scale in a more predictable manner.
Drop me your questions related to this spring boot webflux tutorial.
Реактивное программирование со Spring Boot 2. Часть 1 16.11.2017 12:04
Не так давно вышла новая версия самого популярного фреймворка на Java: Spring Framework 5. Новая версия принесла много нового. Одно из самых больших нововведений — модель реактивного программирования. Совсем скоро выйдет Spring Boot 2, который существенно упростит создание микросервисов c данным подходом.
Если вы, как и я, хотите разобраться подробнее, что это такое и как это используется, то добро пожаловать под кат. Статья делится на две части — теоретическую и практическую. Сейчас мы постараемся разобраться, что значит быть реактивным. После чего попробуем использовать полученные знания для написания собственного микросервиса (часть 2).
Что такое реактивность?
Для начала рассмотрим понятие реактивности. И тут нужно сделать сразу четкое разраничение в определениях.
Реактивная система
Реактивная система — архитектурный паттерн, который удовлетворяет некоторому набору правил (reactive manifesto). Данный монифест был разработан в 2013 году для устранения неопределенности. Дело в том, что на тот момент в Европе и США термин «reactive» являлся слишком избочным. Каждый понимал по-своему какую систему можно назвать реактивной. Это рождало огромную путаницу и в итоге был создан манифест, который устанавливает четкие критерии реактивной системы.
Посмотрим на картинку из манифеста и разберем более подробно, что означает каждый пункт:
- Responsive. Данный принцип говорит нам о том, что разрабатываемая система должна отвечать быстро и за определенное, заранее заданное, время. Кроме того система должна быть достаточно гибкой для самодиагностики и починки.
Что это значит на практикте? Традиционно при запросе некоторого сервиса мы идем в базу данных, вынимаем необходимый объем информации и отдаем ее пользователю. Здесь все хорошо, если наша система достаточно быстрая и база данных не очень большая. Но что, если время формирования ответа гораздно больше ожидаемого? Кроме того, у пользователя мог пропасть интернет на несколько миллисекунд. Тогда все усилия по выборке данных и формированию ответа пропадают. Вспомните gmail или facebook. Когда у вас плохой интернет, вы не получаете ошибку, а просто ждете результат больше обычного. Кроме того, этот пункт говорит нам о том, что ответы и запросы должны быть упорядочены и последовательны.
Реактивное программирование
Если верить википедии, то реактивное программирование — парадигма программирования, ориентированная на потоки данных. Очень скоро мы разберем как это работает на практике, но вначале посмотрим на чем основана данная парадигма.
Основная концепция реактивного программирования базируется на неблокирующем вводе/ввыоде. Обычно при обращении к некоторому ресурсу (базе данных, файле на диске, удаленному серверу и т.д.) мы получаем результат сразу же (часто в той же строчке). При неблокирующем обращении к ресурсу наш поток не останавливается на обращении и продолжает выполнение. Результат мы получаем позже и по необходимости.
Практика
Отлично! Теперь приступим к реализации реактивного программирования в Java. Единственное, следует заметить, что мы будем использовать Spring WebFlux. Это новый фреймворк для реактивного программирования. Возникает вопрос: почему команда Spring не использовала для этих целей Spring Web MVC? Дело в том, что далеко не все модули в этом фреймворке можно использовать для работы в реактивном режиме. Останается много кода и сторонних библитек, например, Tomcat, которые основы на декларативном программировании и потоках.
В процессе работы над фреймворком была разработана небольшая спецификация для асинхронной работы. В дальнейшем эту спецификацию решили включить в Java 9. Однако я буду использовать Java 8 и Spring Boot 2 для простоты.
Основные концепции
В новом подходе у нас есть два основных класса для работы в реактивном режиме:
- Mono
Класс Mono нужен для работы с единственным объектом. Давайте посмотрим как будет выглядеть простое приложение с использованием Mono. Для этого создадим проект и сущность User в нем (все настройки и примеры можно найти на моем профиле в github):
Далее создадим класс с тестами и подготовленными пользователями:
Напишем тест:
Как видно из примера — использовать реактивный подход довольно просто.
Кроме того, у класса Mono есть множество методов на любой случай жизни. Например, есть всем известный метод map для преобразования одного типа в другой:
Данный класс схож с Mono, но предоставляет возможность асинхронной работы со множеством объектов:
Как и в случае с Mono у Flux есть набор полезных методов:
Здесь следует подчеркнуть одну особенность. В отличае от стандартных (не демонов) потоков, при завершении работы основного потока выполнения, сбор наших данных останавливается и программа завершается. Это можно легко продемострировать. Следующий код ничего не выведет на консоль:
Этого можно избежать с помощью класса CountDownLatch:
Все это очень просто и эффективно по ресурсам. Представьте чего можно достить при комбинировании вызовов методов стрима.
В данной статье мы рассмотрели понятие рективностивной системы и реактивного программирования. Кроме того, мы поняли как связаны эти понятия. В следующей части мы пойдем дальше и попробуем построить свой сервис на основе полученных знаний.
Spring Boot 2 – An overview: All those “little” updates and improvements
Upgrades to the latest version of supported libraries and tools, enhancements through and with Spring Framework 5, and changes to the heart of Spring Boot. The second major release of Spring Boot leaves no stone unturned. The last part of this series focuses on some “minor” changes and improvements in Spring Boot 2.
Java 8 baseline and Java 9+ support
Spring Boot 2 is based on the Spring Framework 5 and therefore requires Java 8. Conversely, this signifies that Spring Boot 2 cannot run on Java 7 or older versions of the programming language. Spring Framework 5 is fully compatible with Java Development Kit 9 (JDK 9), both in development and deployment, and works on both the class and module paths.
But what about Jakarta EE / Java EE?
Spring Framework 5 requires the Java EE 7 API and supports the Java EE 8 API at runtime. This means that at least Tomcat 8.5, Jetty 9.4 or WildFly 10 are required. Servlet 4, Validation 2.0, JPA 2.2 and JSON Binding 1.0 are also supported and have been tested extensively.
Spring Framework 5
Upgrading to Spring Framework 5 removes several deprecated classes and features including Hibernate 3 and 5, Tiles 3, Portlet, Velocity, JasperReports, XMLBeans, JDO and Guava in particular. If your application relies on one or more of these features, better stick to the Spring Boot 1.5.x release cycle. Furthermore, Spring Framework 5 brings new features: interfaces are consistently annotated with Nullable or NotNullable and the core container supports functional bean registration (the 4th possibility to build components according to XML, annotations and the explicit Java configuration).
Updated Web MVC and a completely revamped WebFlux
I already presented the new WebFlux module in detail, but the Web MVC was also updated: It supports the Servlet 4.0 specification, is now independent of the Java Activation Framework, can bind immutable objects and much more.
Kotlin support
Spring Framework 5 has first-class support for Kotlin based on a domain-specific language (DSL). It is used to configure the application context, to route WebFlux and for a multitude of adaptations regarding language features. These features include reified types to avoid constant casting.
JUnit 5
While Spring Boot 2 still uses JUnit 4 for testing by default, it fully supports the JUnit Jupiter platform via Spring Framework 5 and provides SpringExtension , @SpringJUnitConfig and more. Plus: If you want to annoy your colleagues, you may make use of @EnabledIf or @DisabledIf on the CI server.
Further notable updates
Major updates of the following dependencies have also been applied:
- Thymeleaf 3 is now not only supported, but default. This can result in some work if your application uses its own dialects.
- Flyway is now used in version 5.
- The update to Hibernate 5.2 will force you to take another look at your entity mapping code.
Changes in Spring Boot 2
- @ConfigurationProperties are only validated if they are marked as @Validated .
- The binding mechanism has been completely rewritten and can be used in a trivial way if you want to test and bind properties very early as part of a starter.
- All properties, packages and classes used in the context of an embedded servlet container have been restructured and now reflect the dualism of Spring Web MVC and WebFlux.
- There is a practical new starter: spring-boot-starter-json . This will load and register all libraries Json needs to process Java-8 data types.
- Spring Boot now uses HikariCP as the default pool for database connections.
- If Hibernate is used in combination with an embedded database, spring.jpa.hibernate.ddl-auto is only set to create-drop if no schema manager like Flyway or Liquibase is involved.
- Custom starters are affected by a small but important change: @ConditionalOnBean now uses AND instead of OR to link multiple, specified beans.
Conclusion
A Hello World application will easily be migrated. In most cases, however, applications in the real world consist of more than one endpoint. The numerous upgrades of upstream libraries alone should be treated with caution.
There is nothing wrong with setting up new services using Spring Boot 2. It has now been in development for over a year and as the author of a book on the subject, it was an interesting experience to accompany this development. However, an existing application should not be updated simply by changing a version number in the build file.
Started as a dare, ended as a feature in @springboot 2.0! Animated Banners 😍 #SpringOne pic.twitter.com/PqSDSWHMze
As a reward for upgrading, there are reactive applications, modern platforms and last but not least: animated banners (see Tweet). So now I know which topic I can take up as an example for my own starters in 2018.
Java Spring Boot
Уроки Java Spring Boot / #1 – Создание веб-сайта на Java
Видеоурок
Полезные ссылки:
Информация про Java Spring Boot
Платформа Java Spring Boot была впервые выпущена в 2004 году. С тех пор платформа постоянно обновляется и пополняется новыми функциями. На сегодняшний день платформа является наиболее продвинутым фреймворком для создания веб сайтов на основе языка Java.
C первых дней выпуска Spring был тепло встречен разработчиками Java, так как это был первый достойный конкурент технологии JavaBeans . JavaBeans, как и Spring, предоставляют набор различных решений для реализации веб проектов.
На основе Spring Boot вы можете создавать веб сайты различных жанров и возможностей. Вы можете создать простой одностаничник или крупный веб проект для какого-либо международного банка.
Spring содержит хорошо описанную документацию, а также множество готовых решений, что можно копировать и использовать в своих проектах.
Технология MVC
Spring реализует шаблон проектирования MVC. MVC расшифровывается как «model-view-controller» или же модель вид контроллер. Данный шаблон позволяет структурировать все файлы внутри проекта и делает чтобы каждый файл отвечал лишь за свою часть работы.
Рассмотрим простой запрос к веб сайту, написанному на Spring Boot. Когда пользователь переходит на какую-либо страницу сайта, то переход отслеживается в контроллере. Контроллер понимает по какому URL адресу перешёл пользователь и далее обращается к модели. Модели могут обратиться к базе данных, получить оттуда какие-то значение, выполнить различные вычисления и далее вернуть эти данные обратно в контроллер. Далее контроллер передает все данные в шаблон, который как раз и показывается пользователю. Шаблон в свою очередь представляет из себя простую HTML страницу с различными текстами, кнопками, картинками и прочим.
Таким образом, приложение делиться на три части, каждая из которых выполняет свою роль в проекте.
Создание проекта
Создать пустой шаблонный проект можно самому или же можно воспользоваться специальным сайтом для подготовки готового проекта. Если создавать пустой проект самому, то необходимо следовать официальной документации .
В случае использования сервиса Start Spring.io вы можете выбрать нужные для вас пакеты, после чего нажать на клавишу «Generate» для генерации и скачивания архивного проекта.
Чтобы открыть проект вы можете воспользоваться любой средой разработки, к примеру программой IntelliJ IDEA .
План курса
В ходе курса мы научимся работать с Java Spring Boot. Мы рассмотрим все основные моменты при работе с данным фреймворком. За курс мы создадим множество шаблонов, рассмотрим работу с шаблонизаторами, рассмотрим работу с базой данных, а также создадим небольшой полноценный проект по типу веб-блога.
К концу курса у вас будет достаточно знаний чтобы начать разрабатывать сайты на основе Java Spring.
Перед изучением курса вам необходимо ознакомиться с языками для вёрстки сайта: HTML , CSS и JavaScript . Также вам необходимо обладать навыками работы с языком Java прежде чем изучать платформу Спринг. Все дополнительные курсы можно посмотреть на нашем ресурсе.