Spring initializer что это
Топ-5 возможностей Spring Boot, которые должны знать Java-разработчики
Возможно, вы слышали о Spring Boot и его магических силах при создании веб-приложения Spring длиной до 140 символов, которые можно написать в твите, но что это на самом деле означает? Какие функции предоставляют Spring Boot такую мощь и делают разработку приложений Spring такой простой? Хорошо, это то, что вы узнаете в этой статье, но если вы спешите, позвольте мне рассказать вам, что вы узнаете об автоконфигурации Spring Boot, зависимостях Starter, CLI Spring Boot, Actuator и Spring Initializer. Это функция, которая устраняет большую часть боли и трений, связанных с написанием Java-приложения на основе Spring.
Но, прежде чем углубляться в эту деталь, давайте вернемся к проблемам, связанным с Java-разработкой на основе Spring. Мне лично нравится сначала видеть проблему и чувствовать ее прежде, чем я смогу насладиться ее решением. Помните, что комфорт чувствуется лучше только после тяжелой работы, так же как и еда, вам больше нравится, когда вы голодны.
Spring, несомненно, является отличным фреймворком, он делает много вещей для вас, например, он создает объект для вас, он предоставляет им их зависимость, он забирает много кода, который вы написали бы, если Spring не существует, но взамен он также требует от вас многого в плане конфигурации и обучения.
Если вы когда-либо работали в новом проекте, где вы с нуля запустили новое Java-приложение на базе Spring, вы знаете, что это не просто. Сначала нужно найти все необходимые зависимости, а затем их совместимую версию. Вам также необходимо настроить множество bean-компонентов, чтобы активировать магию Spring.
Например, если вы хотите создать REST-приложение на основе Spring MVC, которое поддерживает формат JSON во встроенном tomcat, то в вашем файле Maven pom.xml должно быть как минимум 8-10 зависимостей, например spring-core.jar, spring-mvc.jar, jackson.jar, embedded-tomcat.jar и т. д., и учтите, что это очень простая установка.
Spring Boot просто устраняет все эти трудности и позволяет вам написать код, который имеет значение, т.е. код приложения. Все функции Spring Boot, которые я упомянул, например, автоконфигурирование, POM для Starter или зависимость от Starter и Spring Boot CLI, направлены на упрощение разработки Java с помощью Spring.
Теперь давайте углубимся в подробности о каждой из этих функций.
1. Автоконфигурация
Возможно, вы работали с веб-приложением на основе Spring, которое подключается к реляционной базе данных, например, к базе данных в памяти, такой как H2, и если да, то вы можете знать, что вам нужно объявить JdbcTemplate как bean-компонент, а также настроить источник данных, который является зависимость для JdbcTempalte.
В современном приложении Spring, которое использует configuration основе Java, вам нужно добавить следующие два метода в ваш
Класс конфигурации:
Spring Boot — Самозагрузка
В этой главе объясняется, как выполнить загрузку в приложении Spring Boot.
Spring Initializer
Одним из способов начальной загрузки приложения Spring Boot является использование Spring Initializer. Для этого вам нужно посетить веб-страницу Spring Initializer www.start.spring.io и выбрать свою версию сборки, Spring Boot и платформу. Кроме того, вам нужно предоставить Группу, Артефакт и необходимые зависимости для запуска приложения.
Обратите внимание на следующий снимок экрана, на котором показан пример, в котором мы добавили зависимость spring-boot-starter-web для записи конечных точек REST.
Этот раздел объясняет вам примеры, используя Maven и Gradle.
специалист
После загрузки проекта разархивируйте файл. Теперь ваш файл pom.xml выглядит так, как показано ниже —
Gradle
Как только вы загрузите проект, разархивируйте файл. Теперь ваш файл build.gradle выглядит так, как показано ниже —
Зависимости пути класса
Spring Boot предоставляет несколько стартеров для добавления банок в наш путь к классам. Например, для написания конечной точки отдыха нам нужно добавить зависимость spring-boot-starter-web в путь к классам. Для лучшего понимания соблюдайте приведенные ниже коды.
Maven зависимость
Gradle зависимость
Основной метод
Написать конечную точку отдыха
Чтобы написать простую конечную точку отдыха Hello World в самом файле основного класса Spring Boot Application, выполните следующие действия:
Во-первых, добавьте аннотацию @RestController вверху класса.
Во-первых, добавьте аннотацию @RestController вверху класса.
Spring Initializr Reference Guide
Authors
Part I. Spring Initializr Documentation
This section provides a brief overview of the Spring Initializr reference documentation: think of it as map for the rest of the document. Some sections are targeted to a specific audience so this reference guide is not meant to be read in a linear fashion.
Spring Initializr provides a simple web UI to configure the project to generate and endpoints that you can use via plain HTTP: you can see our default instance at start.spring.io. The service allows you to customize the project to generate: the build system and its coordinates, the language and version, the packaging and finally the dependencies to add to the project. The latter is a core concept: based on the chosen Spring Boot version, a set of dependencies can be chosen, usually Spring Boot starters, that will have a concrete impact on your application. More details in the Part II, “User Guide” section.
You can easily create your own instance of the Initializr, by using the jars as libraries in your own app. There is minimal code involved and the service has a very rich configuration structure, allowing you to define not only the values of various project attributes but also the list of dependencies and the constraints to apply to them. If that sounds interesting, then Part III, “Configuration Guide” has all the details you need. You might only want to modify an existing instance of the Initializr, e.g. to add a new dependency type, or update the version of an existing one. For those and other simple and common use cases check out Chapter 8, ‘How-to’ guides.
The Initializr also provides an extensible API to generate quickstart projects, and to inspect the metadata used to generate projects, for instance to list the available dependencies and versions. The API can be used standalone or embedded in other tools (e.g. it is used in Spring Tool Suite, and in the IntelliJ IDEA and Netbeans plugins for Spring Boot). These features are covered in Part IV, “API Guide”.
1. About the documentation
The Spring Initializr reference guide is available as html. The latest copy is available at docs.spring.io/initializr/docs/current/reference.
Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
2. Getting help
Having trouble with Spring Initializr, We’d like to help!
All of Spring Initializr is open source, including the documentation! If you find problems with the docs; or if you just want to improve them, please get involved.
Part II. User Guide
If you’re wondering how to use start.spring.io or what features are available, this section is for you! You’ll find the various way you can interact with the service and get a better insight at what you can do with it.
3. Getting Started
Let’s create a first project and discover the various options that you can use to tune it. Go to start.spring.io, change the Group field from «com.example» to «org.acme» and put the focus in the Dependencies field on the right hand side. If you type «web», you will see a list of matching choices with that simple criteria. Use the mouse or the arrow keys and Enter to select the «Web» starter.
Your browser should now be in this state:
The Spring Boot version above probably doesn’t match the one you have. As we will see later, start.spring.io is continuously updated as new Spring Boot versions are published and the service uses the latest version by default.
Because Spring Initializr has detected it is a web application, a static and templates directories have been created to hold your static resources and ui templates.
3.1 Advanced options
Next to the Generate Project you’ll find a «Switch to the full version» link. If you click on that, you’ll see all the available options. Let’s browse through them quickly:
If you keep on scrolling, you’ll discover all the dependencies that you can find using the search box on the right. You’ll probably notice that some dependencies are greyed out in the UI, meaning that they aren’t available because they require a specific Spring Boot version. We’ll tackle that in the next section.
3.2 Dependencies
The UI allows you to select the Spring Boot version you want to use. You may want to be conservative and keep the default which corresponds at all times to the latest stable release. Or you may want to chose a milestone or snapshot of the next major version. Either way, you’ll notice that certain dependencies become available and others aren’t anymore when you change the version.
If you are searching for a dependency that you know to be available and you get no result, it’s worth looking in the advanced section if that dependency is available in the Spring Boot version that is currently selected.
You may find it is not the case with a message that looks like the following:
Concretely, this defines a «version range» that states the dependency is deprecated and is no longer available as of Spring Boot 1.5. You may want to check the release notes of the related project to understand what your migration path can be. Alternatively, the message could be:
That version range means the dependency is not available with the current Spring Boot generation. Obviously, if you select Spring Boot 2.0 (or later if available), you’ll be able to select that dependency.
3.3 Tuning default values
The Initializr service is configured to offer default values so that you can generate a new project with minimum fuss. Maybe you are a Kotlin fan? Or a Gradle fan? Currently start.spring.io defaults to Java and Maven but it also allows you to tune these defaults easily.
You can share or bookmark URLs that will automatically customize form inputs. For instance, the following URL changes the default to use Kotlin and Gradle:
The following attributes are supported:
The same default rules will apply if a property is overridden. For instance, if the Group is customized, it will automatically customize the root package as well.
The Spring Boot version and the list of dependencies cannot be customized that way as they evolve quite frequently.
4. Command line support
The result is a textual representation of the capabilities of the service that are split in three sections:
First, a table that describes the available project’s types. On the default instance, you’ll find the maven-project and gradle-project we’ve discussed above but you’ll also be able to generate only a build script rather than an entire project.
Then, a table that describes the available parameters. For the most part, these are the same options as the ones available in the web UI. There are, however, a few additional ones:
Finally, the list of dependencies are defined. Each entry provides the identifier that you’ll have to use if you want to select the dependency, a description and the Spring Boot version range, if any.
Alongside the capabilities of the service, you’ll also find a few examples that help you understand how you can generate a project. These are obviously tailored to the client that you are using.
The exact same project can be generated using the http command as well:
HTTPie reads the same hint as the browser so it will store a demo.zip file in the current directory, with the same differences discussed above.
5. IDEs support
Spring Initializr is also integrated in all major Java IDEs and allows you to create and import a new project without having to leave the IDE for the command-line or the web UI.
The following IDEs have dedicated support:
Refer to the documentation of your favorite IDE for more details.
6. Spring Boot CLI support
The spring command line tool defines an init command that allows you to create a project using Spring Initializr.
Part III. Configuration Guide
This section describes how you can create your own instance of the service and tune it for your needs, and also how you can configure an existing instance. You’ll also find some advanced tips to make sure the available options are consistent with the chosen Spring Boot generation.
7. Creating your own instance
Spring Initializr is split across three main modules:
Because it contains several auto-configurations, creating your own instance is quite easy, actually you could get started using Spring Initializr itself to generate a starting point!
Create a new project with the web dependency and add the following dependency:
Or if you are using Gradle:
If you start the application, you’ll see the familiar interface but none of the drop down lists have values (except the one for the Spring Boot version, we will come back to that later). In the rest of this section, we will configure those basic settings.
7.1 Configuring basic settings
Let’s configure the languages and the Java versions we want to support:
If you click on the «Switch to the full version» link, the two drop down lists now offer the options and default values defined above.
The available packagings are also configurable that way:
These two packaging types are the only one explicitly supported at the moment.
7.2 Configuring available Spring Boot versions
If you look at the project home page for Spring Boot, the latest versions are displayed. And you’ve probably noticed that they match the drop down list that you automatically get with a default instance of the Initializr. The reason for that is that Spring Initializr calls an API on spring.io to retrieve the latest versions automatically. This makes sure that you always get the latest available versions.
If you are behind a proxy, or need to customize the RestTemplate that is used behind the scenes, you can define a RestTemplateCustomizer bean in your configuration. For more details, check the documentation.
If you don’t want the version to be upgraded automatically, you need to override the InitializrMetadataProvider bean to provide your own metadata for the service. For instance, you could swap to an implementation that always returns the contents of static application.yml :
The thing to remember is that, by default, you don’t have to worry about upgrading your instance when a new Spring Boot version is released. However, you may need to configure caching to avoid requesting that service too often.
7.3 Configuring available project types
The available project types mostly define the structure of the generated project and its build system. Once a project type is selected, the related action is invoked to generate the project.
By default, Spring Initializr exposes the following resources (all accessed via HTTP GET):
Each type also defines one or more tags that provides additional metadata entries to qualify the entry. The following standard tags exist:
You can of course implement additional endpoints that generate whatever project structure you need but, for now, we’ll simply configure our instance to generate a Gradle or a Maven project:
If you intend to build a custom client against your service, you can add as many tags as you want, and process them in the client in a way that makes sense for your users.
For instance, the spring boot CLI uses them as a shortcut to the full type id. So rather than having to create a Gradle project as follows:
You can simply define a more convenient build parameter:
With that configuration, you should be able to generate your first project, congratulations! Let’s now add dependencies so that you can start searching for them.
7.4 Configuring dependencies
The most basic dependency is composed of:
For instance, the following configures the spring-boot-starter-web Starter:
Each dependency is contained in a group that gathers dependencies sharing a common surface area or any other form of grouping. In the example above, a Web group holds our unique dependency. A group can also provide default values for various settings, see the dedicated how-to for more details.
In our spring-boot-starter-web example above, the dependency is managed by Spring Boot so there is no need to provide a version attribute for it. You’ll surely need to define additional dependencies that are not provided by Spring Boot and we strongly recommend you to use a Bill Of Materials (or BOM).
If no BOM is available you can specify a version directly:
If you add this configuration and search for «acme» (or «solid»), you’ll find this extra entry; generating a maven project with it should add the following to the pom:
The rest of this section will detail the other configuration options.
7.4.1 Availability (version range)
By default, a dependency is available regardless of the Spring Boot version you have selected. If you need to restrict a dependency to a certain Spring Boot generation you can add a versionRange attribute to its definition. A version range is a range of versions of Spring Boot which are valid in combination with it. The versions are not applied to the dependency itself, but rather used to filter out the dependency, or modify it, when different versions of Spring Boot are selected for the generated project.
A typical version is composed of four parts: a major revision, a minor revision, a patch revision and a qualifier. Qualifiers are ordered as follows:
snapshots are in a bit special in that scheme as they always represents the «latest state» of a release. M1 represents the most oldest version for a given major, minor and patch revisions.
A version range has a lower and an upper bound, and if the bound is inclusive it is denoted as a square bracket ( [ or ] ), otherwise it is exclusive and denoted by a parenthesis ( ( or ) ). For instance [1.1.6.RELEASE,1.3.0.M1) means from all versions from 1.1.6.RELEASE up to but not including 1.3.0.M1 (concretely no including the 1.3.x line and after).
Snapshots are naturally ordered higher than released versions, so if you are looking to match a dependency to only the latest snapshots of Spring Boot, you could use a version range of 1.5.x.BUILD-SNAPSHOT (assuming 1.5 was the latest).
Remember to quote the values of a version range in YAML configuration files (with double quotes «»).
See below in the section on linking versions for more examples and idioms.
7.4.2 Repository
If the dependency is not available on Maven Central (or whatever default repository that is configured on your end), you can also add a reference to a repository. A repository is declared at the top level (under env ) and given an id via the key in the configuration:
Once defined, the repository can then be referred back to in a dependency
It is usually preferable to have a BOM for every dependency, and attach the repository to the BOM instead.
The snapshots and milestones repositories on repo.spring.io are automatically available with the spring-snapshots and spring-milestones identifiers respectively.
7.5 Configuring Bill of Materials
In the Initializr a BOM is declared at the env level, and given an id through the configuration key. Example:
If a BOM requires a special, non-default repository, then it can be referred to here, instead of having to explicitly list the repository again for each dependency. A dependency, or a dependency group, can declare that it requires the use of one or more BOMs by referring to the id:
7.5.1 Map coordinates according to the Spring Boot version
In addition to a Spring Boot version range for the dependency or a BOM, you can configure the version relationships at a finer grained level using version mappings. A dependency or BOM has a list of «mappings», each of which consists of a version range, and a set of one or more dependency properties to override for those versions of Spring Boot. You can use a mapping to switch the version of a dependency, or (better) the BOM, or to change its artifact id (if the project changed its packaging) for instance.
Here’s an example of a BOM with mappings:
The primary use case here is to map Spring Boot versions to the preferred or supported versions of the Foo project. You can also see that for the milestone and snapshot BOMs, additional repositories are declared because those artifacts are not in the default repository.
We also use the x trick in version ranges to avoid updating the range every time a new Spring Boot 1.5 bug fix release is available
See below in the section on linking versions for more examples.
7.5.2 Aliases
A dependency has an id (e.g. «web-services»), but it could be necessary to provide a new id and still be able to serve request from client using the now deprecated id. To do so, an alias can be defined for ths dependency;
7.5.3 Facets
A «facet» is a label on a dependency which is used to drive a code modification in the generated project. In the standard Initializr generator, there is only one facet that is actually used ( web ), but custom installations might choose to use it for their own purposes. The web facet is used to drive the inclusion of spring-boot-starter-web if any other dependency with that facet is included. The value of the «facets» property of a dependency is a list of strings.
7.5.4 Links
The following rel value are currently officially supported:
The url can be templated if its actual value can change according to the environment. An URL parameter is specified with curly braces, something like example.com/doc/
The following attributes are currently supported:
Here is an example that adds two links to the acme dependency:
7.5.5 Improve search results
Each dependency can have a weight (a number >=0) and also keywords (list of string) that are used to prioritize them in the search feature in the web UI. If you type one of the keywords into the «Dependencies» box in the UI, those dependencies will be listed below, in order of decreasing weight, if they have one (unweighted dependencies come last).
8. ‘How-to’ guides
This section provides answers to some common ‘how do I do that…’ type of questions that often arise when configuring Spring Initializr.
8.1 Add a new dependency
To add a new dependency, first identify the Maven co-ordinates of the dependency you want to add ( groupId:artifactId:version ) and then check which versions of Spring Boot it works with. If there are multiple versions that work with different versions of Spring Boot, then that’s fine too.
8.2 Override the version of a dependency
Sometimes it happens that the BOM that normally manages your dependency version is in conflict with the newest version. Or maybe this is the case for only a range of Spring Boot versions. Or maybe there just is no BOM, or it’s not worth creating one for just one dependency. In these cases you can specify the version manually for a dependency either at the top level, or in a version mapping. At the top level it looks like this (just a version property in a dependency):
8.3 Link a Boot version to a version of your dependency
If your dependency requires a specific version of Spring Boot, ot different versions of Spring Boot require different versions of your dependency there are a couple of mechanisms to configure that.
The simplest is to put a versionRange in the dependency declaration. This is a range of versions of Spring Boot, not of your dependency. For example:
In this example Foo is available for Spring Boot 1.2.0 (or any milestone of 1.2.0) or greater, and Bar is available for Spring Boot 1.5.0 up to, but not including 2.0.0.
If different versions of your dependency work with different versions of Spring Boot, that’s when you need the mappings property. A mapping is a combination of a versionRange and some or all of the other properties of the dependency, overriding the values defined at the top level. For example:
A mapping can also be applied to a BOM declaration. For example:
In this example Spring Boot versions up to 1.1.6 select version 1.0.0 of the BOM, and set a different repository. Spring Boot versions 1.2.1 and above select 2.0.0 of the BOM and yet another repository.
8.4 Configure a snapshot repository
A dependency, or a BOM, might require the use of a specific repository, if the default one (usually Maven Central) does not contain the artifacts. Normally, the best place to declare that is in the BOM configuration, but if there isn’t a BOM then you can put it in the dependency itself. You can also use a Spring Boot version mapping to override the default repository for a dependency or BOM.
8.5 Make sure a regular dependency brings the base starter
If a dependency does not stand on its own (and specifically if it does not depend on an existing Spring Boot starter) you can flag it as a «non starter»:
When a project is generated that only has dependencies with this flag set, then the base Spring Boot starter is added as well.
8.6 Share common dependency settings in a group
These dependencies, by default, will be available only for Spring Boot versions 1.3 up to 2.0 (excluded) and will bring in the stuff-bom BOM.
9. Advanced configuration
9.1 Caching configuration
Or if you are using Gradle:
You’ll notice that the log entry is much more rare. If you do not want to use JSR-107, you should configure the cache yourselves. Here are the caches used by the application (each one will require some configuration to get it working):
Table 9.1. Cache configuration
Cache the full metadata of the service. When the metadata expires, it is fully resolved again (including a check on spring.io for the latest Spring Boot versions). Adapt the expiration settings accordingly.
Cache dependency-specific metadata.
Cache resources that are used to generate projects.