Spring boot devtools что это
Spring Boot includes an additional set of tools that can make the application development experience a little more pleasant. The spring-boot-devtools module can be included in any project to provide additional development-time features. To include devtools support, simply add the module dependency to your build:
repackaged archives do not contain devtools by default. If you want to use certain remote devtools feature, you’ll need to disable the excludeDevtools build property to include it. The property is supported with both the Maven and Gradle plugins.
20.1 Property defaults
Several of the libraries supported by Spring Boot use caches to improve performance. For example, template engines will cache compiled templates to avoid repeatedly parsing template files. Also, Spring MVC can add HTTP caching headers to responses when serving static resources.
Whilst caching is very beneficial in production, it can be counter productive during development, preventing you from seeing the changes you just made in your application. For this reason, spring-boot-devtools will disable those caching options by default.
Cache options are usually configured by settings in your application.properties file. For example, Thymeleaf offers the spring.thymeleaf.cache property. Rather than needing to set these properties manually, the spring-boot-devtools module will automatically apply sensible development-time configuration.
For a complete list of the properties that are applied see DevToolsPropertyDefaultsPostProcessor.
20.2 Automatic restart
Applications that use spring-boot-devtools will automatically restart whenever files on the classpath change. This can be a useful feature when working in an IDE as it gives a very fast feedback loop for code changes. By default, any entry on the classpath that points to a folder will be monitored for changes. Note that certain resources such as static assets and view templates do not need to restart the application.
Triggering a restart
You can also start your application via the supported build plugins (i.e. Maven and Gradle) as long as forking is enabled since DevTools need an isolated application classloader to operate properly. Gradle and Maven do that by default when they detect DevTools on the classpath.
Automatic restart works very well when used with LiveReload. See below for details. If you use JRebel automatic restarts will be disabled in favor of dynamic class reloading. Other devtools features (such as LiveReload and property overrides) can still be used.
DevTools relies on the application context’s shutdown hook to close it during a restart. It will not work correctly if you have disabled the shutdown hook ( SpringApplication.setRegisterShutdownHook(false) ).
DevTools needs to customize the ResourceLoader used by the ApplicationContext : if your application provides one already, it is going to be wrapped. Direct override of the getResource method on the ApplicationContext is not supported.
The restart technology provided by Spring Boot works by using two classloaders. Classes that don’t change (for example, those from third-party jars) are loaded into a base classloader. Classes that you’re actively developing are loaded into a restart classloader. When the application is restarted, the restart classloader is thrown away and a new one is created. This approach means that application restarts are typically much faster than “cold starts” since the base classloader is already available and populated.
If you find that restarts aren’t quick enough for your applications, or you encounter classloading issues, you could consider reloading technologies such as JRebel from ZeroTurnaround. These work by rewriting classes as they are loaded to make them more amenable to reloading. Spring Loaded provides another option, however it doesn’t support as many frameworks and it isn’t commercially supported.
20.2.1 Excluding resources
if you want to keep those defaults and add additional exclusions, use the spring.devtools.restart.additional-exclude property instead.
20.2.2 Watching additional paths
You may want your application to be restarted or reloaded when you make changes to files that are not on the classpath. To do so, use the spring.devtools.restart.additional-paths property to configure additional paths to watch for changes. You can use the spring.devtools.restart.exclude property described above to control whether changes beneath the additional paths will trigger a full restart or just a live reload.
20.2.3 Disabling restart
If you don’t want to use the restart feature you can disable it using the spring.devtools.restart.enabled property. In most cases you can set this in your application.properties (this will still initialize the restart classloader but it won’t watch for file changes).
20.2.4 Using a trigger file
If you work with an IDE that continuously compiles changed files, you might prefer to trigger restarts only at specific times. To do this you can use a “trigger file”, which is a special file that must be modified when you want to actually trigger a restart check. Changing the file only triggers the check and the restart will only occur if Devtools has detected it has to do something. The trigger file could be updated manually, or via an IDE plugin.
To use a trigger file use the spring.devtools.restart.trigger-file property.
You might want to set spring.devtools.restart.trigger-file as a global setting so that all your projects behave in the same way.
20.2.5 Customizing the restart classloader
As described in the Restart vs Reload section above, restart functionality is implemented by using two classloaders. For most applications this approach works well, however, sometimes it can cause classloading issues.
The spring-devtools.properties file can contain restart.exclude. and restart.include. prefixed properties. The include elements are items that should be pulled up into the “restart” classloader, and the exclude elements are items that should be pushed down into the “base” classloader. The value of the property is a regex pattern that will be applied to the classpath.
All property keys must be unique. As long as a property starts with restart.include. or restart.exclude. it will be considered.
All META-INF/spring-devtools.properties from the classpath will be loaded. You can package files inside your project, or in the libraries that the project consumes.
20.2.6 Known limitations
Unfortunately, several third-party libraries deserialize without considering the context classloader. If you find such a problem, you will need to request a fix with the original authors.
20.3 LiveReload
The spring-boot-devtools module includes an embedded LiveReload server that can be used to trigger a browser refresh when a resource is changed. LiveReload browser extensions are freely available for Chrome, Firefox and Safari from livereload.com.
You can only run one LiveReload server at a time. Before starting your application, ensure that no other LiveReload servers are running. If you start multiple applications from your IDE, only the first will have LiveReload support.
20.4 Global settings
20.5 Remote applications
The Spring Boot developer tools are not just limited to local development. You can also use several features when running applications remotely. Remote support is opt-in, to enable it you need to make sure that devtools is included in the repackaged archive:
Then you need to set a spring.devtools.remote.secret property, for example:
Enabling spring-boot-devtools on a remote application is a security risk. You should never enable support on a production deployment.
Remote devtools support is provided in two parts; there is a server side endpoint that accepts connections, and a client application that you run in your IDE. The server component is automatically enabled when the spring.devtools.remote.secret property is set. The client component must be launched manually.
20.5.1 Running the remote client application
The remote client application is designed to be run from within your IDE. You need to run org.springframework.boot.devtools.RemoteSpringApplication using the same classpath as the remote project that you’re connecting to. The non-option argument passed to the application should be the remote URL that you are connecting to.
For example, if you are using Eclipse or STS, and you have a project named my-app that you’ve deployed to Cloud Foundry, you would do the following:
A running remote client will look like this:
Because the remote client is using the same classpath as the real application it can directly read application properties. This is how the spring.devtools.remote.secret property is read and passed to the server for authentication.
It’s always advisable to use https:// as the connection protocol so that traffic is encrypted and passwords cannot be intercepted.
If you need to use a proxy to access the remote application, configure the spring.devtools.remote.proxy.host and spring.devtools.remote.proxy.port properties.
20.5.2 Remote update
The remote client will monitor your application classpath for changes in the same way as the local restart. Any updated resource will be pushed to the remote application and (if required) trigger a restart. This can be quite helpful if you are iterating on a feature that uses a cloud service that you don’t have locally. Generally remote updates and restarts are much quicker than a full rebuild and deploy cycle.
Files are only monitored when the remote client is running. If you change a file before starting the remote client, it won’t be pushed to the remote server.
20.5.3 Remote debug tunnel
Java remote debugging is useful when diagnosing issues on a remote application. Unfortunately, it’s not always possible to enable remote debugging when your application is deployed outside of your data center. Remote debugging can also be tricky to setup if you are using a container based technology such as Docker.
To help work around these limitations, devtools supports tunneling of remote debug traffic over HTTP. The remote client provides a local server on port 8000 that you can attach a remote debugger to. Once a connection is established, debug traffic is sent over HTTP to the remote application. You can use the spring.devtools.remote.debug.local-port property if you want to use a different port.
Debugging a remote service over the Internet can be slow and you might need to increase timeouts in your IDE. For example, in Eclipse you can select Java → Debug from Preferences… and change the Debugger timeout (ms) to a more suitable value ( 60000 works well in most situations).
When using the remote debug tunnel with IntelliJ IDEA, all breakpoints must be configured to suspend the thread rather than the VM. By default, breakpoints in IntelliJ IDEA suspend the entire VM rather than only suspending the thread that hit the breakpoint. This has the unwanted side-effect of suspending the thread that manages the remote debug tunnel, causing your debugging session to freeze. When using the remote debug tunnel with IntelliJ IDEA, all breakpoints should be configured to suspend the thread rather than the VM. Please see IDEA-165769 for further details.
Spring Blog
DevTools in Spring Boot 1.3
To use the module you simply need to add it as a dependency in your Maven POM:
or your Gradle build file:
Once included, the spring-boot-devtools module provides a number of nice features that we cover below (If you can’t be bother to read the text, skip to the end of the post for a short video).
Property Defaults
Now, when you use the spring-boot-devtools module, you no longer need to remember to set the properties. During development caching for Thymeleaf, Freemarker, Groovy Templates, Velocity and Mustache are all automatically disabled.
Automatic Restart
You may have used tools such as JRebel or Spring Loaded in the past to provide instant reload for your Java applications. These tools are great, but they do often require additional configuration or IDE plugins to work (and some of them even cost money!)
With Spring Boot 1.3 we’ve been working on something that’s a little slower than these “instant reload” techniques, and instead works by restarting your application. When you have the spring-boot-devtools module included, any classpath file changes will automatically trigger an application restart. We do some tricks to try and keep restarts fast, so for many microservice style applications this technique might be good enough.
LiveReload
With sensible “cache properties” and “automatic restarts” working, needing to manually click the browser refresh button each time something changes starts to become a little tedious. So to help save your mouse buttons, Spring Boot 1.3 DevTools includes an embedded LiveReload server. LiveReload is a simple protocol that allows your application to automatically trigger a browser refresh whenever things change. Browser extensions are freely available for Chrome, Firefox and Safari from livereload.com.
Remote Debug Tunneling
To help with this, Spring Boot 1.3 can tunnel JDWP (the Java Debug Wire Protocol) over HTTP directly to your application. This can even work with applications deployed to Internet Cloud providers that only expose port 80 and 443 (although since JDWP is quite a chatty protocol this can be quite slow).
Remote Update and Restart
The final trick that DevTools offers is support for remote application updates and restarts. This works by monitoring your local classpath for file changes and pushing them to a remote server which is then restarted. As with local restarts, you can also use this feature in combination with LiveReload.
Video Preview
All the features discussed in this post are already available in Spring Boot 1.3.0.M1 and detailed documentation is available in the reference guide. If you’re not ready to install the bits yourself yet, here’s a short video that shows how they work:
Spring Boot Dev Tools
Introduction to Spring Boot Dev Tools
Spring Boot comes with a lot of features and one of such feature is to help in developer productivity. In this post, we will cover about Spring Boot Dev Tools.
Introduction
One of the main advantages of using Spring Boot is its production ready features, to provide these features, Spring Boot use certain pre-defined configurations.
These features are good but can slow down development with frequent changes in our code and want to see changes immediately. We have the option to use 3rd party tools like Jrebel to help in this but these tools are not free and need a significant amount to get a license (Jrebel is really a great tool and if you can get it, I will highly recommend it). Spring Boot 1.3 introduced Spring Boot Dev Tools module, aimed to help developers in improving the productivity. We will cover following features of the Spring Boot Dev Tool
What is Spring Boot Dev Tools?
They introduced spring Boot Dev Tools module in 1.3 to provide a powerful tool for the development. It helps developers to shorten the development cycle and enable easy deployment and testing during the development. To add use the feature, we need to add a spring-boot-devtools dependency in our build. We need to add the following dependency to our Maven POM
if you are using Gradle as your build tool
Once we perform build, it will add a spring-boot-devtools to our project with its developer-friendly features. Let’s explore these features.
2. Property Defaults
Spring Boot comes with many productions-ready features (Also known as auto-configuration) which include caching for its modules for performance. To boost performance, template engines might cache all compiled templates to avoid template parsing on each request. This is helpful once we deploy our application on production but can be problematic during the development (We might not see changes immediately).
3. Automatic Restart
Typically, as a development life-cycle, we change our code, deploy it and test it and if things are not working as expected we will repeat this cycle. We can always use third-party tools like Jrebel to help in this. Spring Boot Dev Tools provide a similar feature (not as quick as Jrebel) to auto restart. Whenever a file changes in the classpath, spring-boot-devtools module will restart application automatically.
When you start your application with dev tools, you will find similar logs on the startup.
change your application code and perform build, it will trigger an automatic restart. Here are the logs from the restart
Spring Boot use 2 class loader internally to handle this restart. we will cover this feature in another post.
3.1 Exclusion
3.2 Disable Restart
If you want to use the spring-boot-devtools module but like to disable restart feature, you can easily customize it by setting spring.devtools.restart.enabled in your application.properties file, you can disable this feature by setting this on the System property.
4. Live Reload
The dev tools come with an embedded LiveReload server which will automatically trigger browser refresh when resource change. Visit livereload.com for more information.
5. Remote Debugging via HTTP
Spring Boot dev tools provide ready to use remote debugging capabilities, to use this feature on the remote application, we have to make sure that devtools in included in the deployment packet. We can achieve this by setting the excludeDevtools property in our POM.xml file
To allow client to allow remote debugging, we need to make sure following steps
[pullquote align=”normal”]For debugging an application using IntelliJ. Please read Remote debug spring boot application with the maven and IntelliJ [/pullquote]
6. Remote Update
Spring Boot development tool also support update and restart for remote application. The remote client will monitor changes in the local classpath and will trigger a restart after pushing these changes to the remote server. This can be a handy feature if your work involves a cloud service.
6. Global Setting
Summary
Spring Boot Dev Tools comes with many built-in features to help in the development life cycle and make development experience better. We learned how to enable by using these features provided under spring-boot-devtools modules.
Как писать на Spring в 2017
В одной из классических статей для новичков, мелькавших недавно на Хабре, рассказывалось про создание базового Web приложения на Java. Все начиналось с сервлета, потом создания JSP страницы и, наконец, деплоймента в контейнер. Посмотрев на это свежим взглядом я понял, что для как раз для новичков это, наверняка, выглядит совершенно жутко — на фоне простых и понятных PHP или Node.js, где все просто — написал контроллер, вернул объект, он стал JSON или HTML. Чтобы немного развеять это ощущение, я решил написать «Гайд для новичков в Spring». Цель это статьи — показать, что создание Web приложений на Java, более того — на Spring Framework это не боль и мучительное продирание через web.xml, persistence.xml, beans.xml, и собирание приложения как карточного домика по кусочкам, а вполне себе быстрый и комфортный процесс. Аудитория — начинающие разработчики, разработчики на других языках, ну и те, кто видел Спринг в его не самые лучше времена.
Введение
В этой статье мы посмотрим, что включает в себя современный Спринг, как настроить локальное окружение для разработки Веб приложений, и создадим простое веб-приложение, которое берет данные из БД и отдает HTML страницу и JSON. Как ни странно, большинство статей (на русском языке) для начинающих, которые я нашел в топе поиска описывают и ручное создание контекста, и запуск приложения, и конфигурацию через XML — ничего из этого в современном Спринге делать, разумеется, не обязательно.
Что такое Spring?
Для начала пара слов, что же такое Spring. В настоящее время, под термином «Spring» часто подразумевают целое семейство проектов. В большинстве своем, они развиваются и курируются компанией Pivotal и силами сообщества. Ключевые (но не все) проекты семейства Spring это:
Spring Framework (или Spring Core)
Ядро платформы, предоставляет базовые средства для создания приложений — управление компонентами (бинами, beans), внедрение зависимостей, MVC фреймворк, транзакции, базовый доступ к БД. В основном это низкоуровневые компоненты и абстракции. По сути, неявно используется всеми другими компонентами.
Spring MVC (часть Spring Framework)
Стоит упомянуть отдельно, т.к. мы будем вести речь в основном о веб-приложениях. Оперирует понятиями контроллеров, маппингов запросов, различными HTTP абстракциями и т.п. Со Spring MVC интегрированы нормальные шаблонные движки, типа Thymeleaf, Freemaker, Mustache, плюс есть сторонние интеграции с кучей других. Так что никакого ужаса типа JSP или JSF писать не нужно.
Spring Data
Доступ к данным: реляционные и нереляционные БД, KV хранилища и т.п.
Spring Cloud
Много полезного для микросервисной архитектуры — service discovery, трасировка и диагностика, балансировщики запросов, circuit breaker-ы, роутеры и т.п.
Spring Security
Авторизация и аутентификация, доступ к данным, методам и т.п. OAuth, LDAP, и куча разных провайдеров.
Типичное веб приложение скорее всего будет включать набор вроде Spring MVC, Data, Security. Ниже мы увидим, как это все работает вместе.
Особняком стоит отметить Spring Boot — это вишенка на торте (а некоторые думают, что собственно сам торт), которые позволяет избежать всего ужаса XML конфигурации. Boot позволяет быстро создать и сконфигурить (т.е. настроить зависимости между компонентами) приложение, упаковать его в исполняемый самодостаточный артефакт. Это то связующее звено, которое объединяет вместе набор компонентов в готовое приложение. Пару вещей, которые нужно знать про Spring Boot:
Настройка окружения
Для того, чтобы создать простое приложение, знать, как создать проект Maven с нуля, как настроить плагины, чтобы создать JAR, какие бывают лейауты в JAR, как настроить Surefire для запуска тестов, как установить и запустить локально Tomcat, а уж тем более, как работает DispatcherServlet — совершенно не нужно.
Современное приложение на Spring создается в два шага:
Spring Initializr позволяет «набрать» в свое приложение нужных компонентов, которые потом Spring Boot (он автоматически включен во все проекты, созданные на Initializr) соберет воедино.
В качестве среды разработки подойдет что угодно, например бесплатная IntelliJ IDEA CE прекрасно справляется — просто импортируйте созданный pom.xml (Maven) или build.gradle (Gradle) файл в IDE.
Стоит отдельно отметить компонент Spring Boot который называется DevTools. Он решает проблему цикла локальной разработки, который раньше выглядел как:
В те древние времена даже родилась поговорка, что Spring это DSL для конвертации XML конфигов в стектрейсы.
С включенными Spring Boot DevTools цикл разработки сокращается до:
DevTools будут автоматом проверять изменения в скомпилированном коде или шаблонах, и очень быстро перезапускать (hot reload) только «боевую» часть приложения (как nodemon, если вы знакомы с миром node.js). Более того, DevTools включают интеграцию с Live Reload и после установки расширения в браузере, достаточно скомпилировать проект в IDEA, чтобы он автоматом обновился в браузере.
Разработка
Окей, пора приступать к практической части. Итак, наша цель — создать веб-приложение, которое отдает welcome страницу, обращается с нее же к собственному API, получает JSON с данными из базы и выводит их в таблицу.
Новый проект
Точнее, контейнер нужен — только он предоставлен и настроен Spring Boot-ом — используя Embedded Tomcat
Контроллер
Итак, наш следующий шаг — создать контроллер и вернуть «домашнюю» страницу. Код контроллера выглядит так просто, как и ожидается:
Пара вещей, на которые стоит обратить внимание.
С Котлин это бы выглядело еще лучше и проще, но это потребует введения сразу большого количества новых понятий — язык, фреймворк. Лучше начинать с малого.
Класс, помеченный как @Controller автоматически регистрируется в MVC роутере, а используя аннотации @(Get|Post|Put|Patch)Mapping можно регистрировать разные пути.
Все файлы из каталога resources/static/ считаются статическими, там можно хранить CSS и картинки.
Шаблон
Мы используем Mustache (Handlebar) синтаксис, поэтому шаблон очень напоминает обычный HTML
После компиляции проекта (⌘/Ctrl + F9) — можно сразу идти на http://localhost:8080 и увидеть созданную страницу.
Доступ к базе
Для начала, опишем нашу предметную область. Мы будем собирать статистику посещений — каждый раз, когда кто-то заходит на главную страницу, мы будем писать это в базу. Модель выглядит до крайности примитивно:
Предвидя череду комментариев «Как же без геттеров и сеттеров» и «Где же equals / hashCode» — эти элементы упущены сознательно с целью упрощения кода. Совершенно чудовищная ошибка дизайна Java которая заставляет писать эту ерунду (геттеры и методы сравнения), это, конечно, отдельный разговор. Котлин эту проблему, кстати, решает.
Мы снова очень активно используем аннотации — в этот раз из Spring Data (точнее, JPA — это дремучая спецификация для доступа к данным). Этот класс описывает модель с двумя полями, одно из которых генерится автоматически. По этому классу будет автоматически создана модель данных (таблицы) в БД.
Теперь для этой модели пора создать репозиторий. Это еще проще, чем контроллер.
Все, репозиторий можно использовать для работы с базой — читать и писать записи. У внимательного читателя должен сработать WTF детектор — что здесь вообще происходит? Мы определяем интерфейс и внезапно он начинает работать с базой? Все так. Благодаря магии Spring Boot и Spring Data «под капотом» происходит следующее:
Чтобы использовать репозиторий в контроллере мы воспользуемся механизмом внедрения зависимостей, предоставляемый Spring Framework. Чтобы это сделать, как ни странно, нужно всего лишь объявить зависимость в нашем контроллере.
Теперь можно писать в базу в методе контроллера.
REST контроллер
Следующий шаг — это вернуть все записи из базы в JSON формате, чтобы потом их можно было читать на клиенте.
На что обратить внимание:
Теперь при запросе http://localhost:8080/api/visits (предварительно скомпилировав проект и дав DevTools обновить приложение) мы получим JSON с нужными данными.
Клиентский код
Оставим за рамками этой статьи, пример можно увидеть в исходном коде. Цель этого кода — исключительно продемонстрировать как получить JSON данные с сервера, интеграции с клиентскими фреймворками React, Angular etc намеренно оставлены вне рамок этой статьи.
Тестирование
Spring так же предоставляет мощные средства для Integration и Unit тестирования приложения. Пример кода, который проверяет контроллер:
Используя абстракции типа MockMvc можно легко тестировать внешний интерфейс приложения, в то же время имея доступ к его внутренностям. Например, можно целиком заменить компоненты приложения на моки (заглушки).
Аналогично для API тестов есть набор хелперов для проверки JsonPath выражений.
Тестирование в Spring это все таки отдельная тема, поэтому мы не будем сильно на этом останавливаться сейчас.
Деплоймент
Чтобы собрать и запустить наше приложение в продакшене есть несколько вариантов.
Таким образом сборка и запуск приложения выглядит как:
Для деплоймента этого JAR файла не нужно ничего, кроме установленной Java (JRE). Это так называемый fat JAR — он включает в себя и встроенный сервлет контейнер (Tomcat по умолчанию) и фреймворк, и все библиотеки-зависимости. По сути, он является единственным артефактом деплоймтента — его можно просто копировать на целевой сервер и запускать там.
Более того, файл можно сделать «выполняемым» и запускать его просто из командной строки (Java, конечно, все равно необходима).
На базе этого файла можно легко создать Docker образ или установить его как демон. Больше деталей доступно в официальной документации.
Заключение
Получилось, все же, очень сжато — но уложить даже самый простой вводный курс по Spring в рамки одной статьи не очень просто. Надеюсь, это поможет кому-то сделать первый шаги в Spring-е, и хотя понять его фундаментальные концепции.
Как вы успели заметить, в тексте статьи много раз звучало слово «магия Spring». По сути своей, это очень «магический» фреймворк — даже взглянув на самую верхушку айсберга мы уже видели, что Spring много всего делает в фоне. Это является и плюсом, и минусом фреймворка. Плюс несомненно в том, что многие сложные вещи (очень многие) можно сделать одной аннотацией или зависимостью. Минус же это скрытая сложность — чтобы решить какие-то сложные проблемы, заставить фреймворк работать в крайних случаях или понимать все тонкости и аспекты нужно его неплохо знать.
Чтобы сделать этап «знать» как можно проще, Spring обладает отличной документацией, огромным сообществом, и чистыми исходниками, которые вполне можно читать. Если расположить Spring на шкале Рича Хики, он (Spring) несомненно попадет в easy, но уж точно не simple. Но для современного энтерпрайза (и не только энтерпрайза) он дает невероятные возможности чтобы получить production-ready приложение очень быстро и концентрироваться на логике приложения, а не инфраструктуры вокруг.