springitspretty翻译_spring in spring翻译

springitspretty翻译_spring in spring翻译“How-to” GuidesThis section provides answers to some common ‘how do I do that…​’ questions that o

“How-to” Guides
  This section provides answers to some common ‘how do I do that…​’ questions that often arise when using Spring Boot.
Its coverage is not exhaustive, but it does cover quite a lot.

  If you have a specific problem that we do not cover here, you might want to check out stackoverflow.com to see if someone has already provided an answer.
This is also a great place to ask new questions (please use the tag).

  We are also more than happy to extend this section.
If you want to add a ‘how-to’, send us a pull request.

  1. Spring Boot Application

  This section includes topics relating directly to Spring Boot applications.

  1.1. Create Your Own FailureAnalyzer

  is a great way to intercept an exception on startup and turn it into a human-readable message, wrapped in a .
Spring Boot provides such an analyzer for application-context-related exceptions, JSR-303 validations, and more.
You can also create your own.

  is a convenient extension of that checks the presence of a specified exception type in the exception to handle.
You can extend from that so that your implementation gets a chance to handle the exception only when it is actually present.
If, for whatever reason, you cannot handle the exception, return to give another implementation a chance to handle the exception.

  implementations must be registered in .
The following example registers :

  If you need access to the or the , your can simply implement or respectively.

  1.2. Troubleshoot Auto-configuration

  The Spring Boot auto-configuration tries its best to “do the right thing”, but sometimes things fail, and it can be hard to tell why.

  There is a really useful available in any Spring Boot .
You can see it if you enable logging output.
If you use the (see the Actuator chapter), there is also a endpoint that renders the report in JSON.
Use that endpoint to debug the application and see what features have been added (and which have not been added) by Spring Boot at runtime.

  Many more questions can be answered by looking at the source code and the Javadoc.
When reading the code, remember the following rules of thumb:

  Look for classes called and read their sources.
Pay special attention to the annotations to find out what features they enable and when.
Add to the command line or a System property to get a log on the console of all the auto-configuration decisions that were made in your app.
In a running application with actuator enabled, look at the endpoint ( or the JMX equivalent) for the same information.

  Look for classes that are (such as ) and read from there the available external configuration options.
The annotation has a attribute that acts as a prefix to external properties.
Thus, has and its configuration properties are , , and others.
In a running application with actuator enabled, look at the endpoint.

  Look for uses of the method on the to pull configuration values explicitly out of the in a relaxed manner.
It is often used with a prefix.

  Look for annotations that bind directly to the .

  Look for annotations that switch features on and off in response to SpEL expressions, normally evaluated with placeholders resolved from the .

  1.3. Customize the Environment or ApplicationContext Before It Starts

  A has and that are used to apply customizations to the context or environment.
Spring Boot loads a number of such customizations for use internally from .
There is more than one way to register additional customizations:

  Programmatically, per application, by calling the and methods on before you run it.

  Declaratively, per application, by setting the or properties.

  Declaratively, for all applications, by adding a and packaging a jar file that the applications all use as a library.

  The sends some special to the listeners (some even before the context is created) and then registers the listeners for events published by the as well.
See “Application Events and Listeners” in the ‘Spring Boot features’ section for a complete list.

  It is also possible to customize the before the application context is refreshed by using .
Each implementation should be registered in , as shown in the following example:

  The implementation can load arbitrary files and add them to the .
For instance, the following example loads a YAML configuration file from the classpath:

  The has already been prepared with all the usual property sources that Spring Boot loads by default.
It is therefore possible to get the location of the file from the environment.
The preceding example adds the property source at the end of the list so that a key defined in any of the usual other locations takes precedence.
A custom implementation may define another order.

While using on your may seem to be a convenient way to load a custom resource in the , we do not recommend it.
Such property sources are not added to the until the application context is being refreshed.
This is too late to configure certain properties such as and which are read before refresh begins.

  1.4. Build an ApplicationContext Hierarchy (Adding a Parent or Root Context)

  You can use the class to create parent/child hierarchies.
See “spring-boot-features.html” in the ‘Spring Boot features’ section for more information.

  1.5. Create a Non-web Application

  Not all Spring applications have to be web applications (or web services).
If you want to execute some code in a method but also bootstrap a Spring application to set up the infrastructure to use, you can use the features of Spring Boot.
A changes its class, depending on whether it thinks it needs a web application or not.
The first thing you can do to help it is to leave server-related dependencies (e.g. servlet API) off the classpath.
If you cannot do that (for example, you run two applications from the same code base) then you can explicitly call on your instance or set the property (through the Java API or with external properties).
Application code that you want to run as your business logic can be implemented as a and dropped into the context as a definition.

  2. Properties and Configuration

  This section includes topics about setting and reading properties and configuration settings and their interaction with Spring Boot applications.

  2.1. Automatically Expand Properties at Build Time

  Rather than hardcoding some properties that are also specified in your project’s build configuration, you can automatically expand them by instead using the existing build configuration.
This is possible in both Maven and Gradle.

2.1.1. Automatic Property Expansion Using Maven

  You can automatically expand properties from the Maven project by using resource filtering.
If you use the , you can then refer to your Maven ‘project properties’ with placeholders, as shown in the following example:

  Only production configuration is filtered that way (in other words, no filtering is applied on ).

If you enable the flag, the goal can add directly to the classpath (for hot reloading purposes).
Doing so circumvents the resource filtering and this feature.
Instead, you can use the goal or customize the plugin’s configuration.
See the plugin usage page for more details.

  If you do not use the starter parent, you need to include the following element inside the element of your :

  You also need to include the following element inside :

  The property is important if you use standard Spring placeholders (such as ) in your configuration.
If that property is not set to , these may be expanded by the build.

2.1.2. Automatic Property Expansion Using Gradle

  You can automatically expand properties from the Gradle project by configuring the Java plugin’s task to do so, as shown in the following example:

  You can then refer to your Gradle project’s properties by using placeholders, as shown in the following example:

  Gradle’s method uses Groovy’s , which transforms tokens.
The style conflicts with Spring’s own property placeholder mechanism.
To use Spring property placeholders together with automatic expansion, escape the Spring property placeholders as follows: .

  2.2. Externalize the Configuration of

  A has bean properties (mainly setters), so you can use its Java API as you create the application to modify its behavior.
Alternatively, you can externalize the configuration by setting properties in .
For example, in , you might have the following settings:

  Then the Spring Boot banner is not printed on startup, and the application is not starting an embedded web server.

  Properties defined in external configuration override the values specified with the Java API, with the notable exception of the sources used to create the .
Consider the following application:

  Now consider the following configuration:

  The actual application now shows the banner (as overridden by configuration) and uses three sources for the (in the following order): , , and .

  2.3. Change the Location of External Properties of an Application

  By default, properties from different sources are added to the Spring in a defined order (see “spring-boot-features.html” in the ‘Spring Boot features’ section for the exact order).

  You can also provide the following System properties (or environment variables) to change the behavior:

  (): Defaults to as the root of the file name.

  (): The file to load (such as a classpath resource or a URL).
A separate property source is set up for this document and it can be overridden by system properties, environment variables, or the command line.

  No matter what you set in the environment, Spring Boot always loads as described above.
By default, if YAML is used, then files with the ‘.yml’ extension are also added to the list.

  Spring Boot logs the configuration files that are loaded at the level and the candidates it has not found at level.

  See for more detail.

  2.4. Use ‘Short’ Command Line Arguments

  Some people like to use (for example) instead of to set configuration properties on the command line.
You can enable this behavior by using placeholders in , as shown in the following example:

  If you inherit from the POM, the default filter token of the has been changed from to (that is, instead of ) to prevent conflicts with Spring-style placeholders.
If you have enabled Maven filtering for the directly, you may want to also change the default filter token to use other delimiters.

In this specific case, the port binding works in a PaaS environment such as Heroku or Cloud Foundry.
In those two platforms, the environment variable is set automatically and Spring can bind to capitalized synonyms for properties.

  2.5. Use YAML for External Properties

  YAML is a superset of JSON and, as such, is a convenient syntax for storing external properties in a hierarchical format, as shown in the following example:

  Create a file called and put it in the root of your classpath.
Then add to your dependencies (Maven coordinates , already included if you use the ).
A YAML file is parsed to a Java (like a JSON object), and Spring Boot flattens the map so that it is one level deep and has period-separated keys, as many people are used to with files in Java.

  The preceding example YAML corresponds to the following file:

  See “spring-boot-features.html” in the ‘Spring Boot features’ section for more information about YAML.

  2.6. Set the Active Spring Profiles

  The Spring has an API for this, but you would normally set a System property () or an OS environment variable ().
Also, you can launch your application with a argument (remember to put it before the main class or jar archive), as follows:

  $ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar

  In Spring Boot, you can also set the active profile in , as shown in the following example:

  A value set this way is replaced by the System property or environment variable setting but not by the method.
Thus, the latter Java API can be used to augment the profiles without changing the defaults.

  See “spring-boot-features.html” in the “Spring Boot features” section for more information.

  2.7. Change Configuration Depending on the Environment

  A YAML file is actually a sequence of documents separated by lines, and each document is parsed separately to a flattened map.

  If a YAML document contains a key, then the profiles value (a comma-separated list of profiles) is fed into the Spring method.
If any of those profiles is active, that document is included in the final merge (otherwise, it is not), as shown in the following example:

  In the preceding example, the default port is 9000.
However, if the Spring profile called ‘development’ is active, then the port is 9001.
If ‘production’ is active, then the port is 0.

The YAML documents are merged in the order in which they are encountered.
Later values override earlier values.

  To do the same thing with properties files, you can use to specify profile-specific values.

  2.8. Discover Built-in Options for External Properties

  Spring Boot binds external properties from (or files and other places) into an application at runtime.
There is not (and technically cannot be) an exhaustive list of all supported properties in a single location, because contributions can come from additional jar files on your classpath.

  A running application with the Actuator features has a endpoint that shows all the bound and bindable properties available through .

  The appendix includes an example with a list of the most common properties supported by Spring Boot.
The definitive list comes from searching the source code for and annotations as well as the occasional use of .
For more about the exact ordering of loading properties, see “spring-boot-features.html”.

  3. Embedded Web Servers

  Each Spring Boot web application includes an embedded web server.
This feature leads to a number of how-to questions, including how to change the embedded server and how to configure the embedded server.
This section answers those questions.

  3.1. Use Another Web Server

  Many Spring Boot starters include default embedded containers.

  For servlet stack applications, the includes Tomcat by including , but you can use or instead.

  For reactive stack applications, the includes Reactor Netty by including , but you can use , , or instead.

  When switching to a different HTTP server, you need to exclude the default dependencies in addition to including the one you need.
Spring Boot provides separate starters for HTTP servers to help make this process as easy as possible.

  The following Maven example shows how to exclude Tomcat and include Jetty for Spring MVC:

  The version of the Servlet API has been overridden as, unlike Tomcat 9 and Undertow 2.0, Jetty 9.4 does not support Servlet 4.0.

  The following Gradle example shows how to exclude Netty and include Undertow for Spring WebFlux:

  is required to use the class, so you may need to keep a dependency on Netty even when you need to include a different HTTP server.

  3.2. Disabling the Web Server

  If your classpath contains the necessary bits to start a web server, Spring Boot will automatically start it.
To disable this behavior configure the in your , as shown in the following example:

  3.3. Change the HTTP Port

  In a standalone application, the main HTTP port defaults to but can be set with (for example, in or as a System property).
Thanks to relaxed binding of values, you can also use (for example, as an OS environment variable).

  To switch off the HTTP endpoints completely but still create a , use (doing so is sometimes useful for testing).

  For more details, see “spring-boot-features.html” in the ‘Spring Boot Features’ section, or the source code.

  3.4. Use a Random Unassigned HTTP Port

  To scan for a free port (using OS natives to prevent clashes) use .

  3.5. Discover the HTTP Port at Runtime

  You can access the port the server is running on from log output or from the through its .
The best way to get that and be sure that it has been initialized is to add a of type and pull the container out of the event when it is published.

  Tests that use can also inject the actual port into a field by using the annotation, as shown in the following example:

  is a meta-annotation for .
Do not try to inject the port in a regular application.
As we just saw, the value is set only after the container has been initialized.
Contrary to a test, application code callbacks are processed early (before the value is actually available).

  3.6. Enable HTTP Response Compression

  HTTP response compression is supported by Jetty, Tomcat, and Undertow.
It can be enabled in , as follows:

  By default, responses must be at least 2048 bytes in length for compression to be performed.
You can configure this behavior by setting the property.

  By default, responses are compressed only if their content type is one of the following:

  You can configure this behavior by setting the property.

  3.7. Configure SSL

  SSL can be configured declaratively by setting the various properties, typically in or .
The following example shows setting SSL properties in :

  See for details of all of the supported properties.

  Using configuration such as the preceding example means the application no longer supports a plain HTTP connector at port 8080.
Spring Boot does not support the configuration of both an HTTP connector and an HTTPS connector through .
If you want to have both, you need to configure one of them programmatically.
We recommend using to configure HTTPS, as the HTTP connector is the easier of the two to configure programmatically.

  3.8. Configure HTTP/2

  You can enable HTTP/2 support in your Spring Boot application with the configuration property.
This support depends on the chosen web server and the application environment, since that protocol is not supported out-of-the-box by JDK8.

  Spring Boot does not support , the cleartext version of the HTTP/2 protocol.
So you must configure SSL first.

3.8.1. HTTP/2 with Undertow

  As of Undertow 1.4.0+, HTTP/2 is supported without any additional requirement on JDK8.

3.8.2. HTTP/2 with Jetty

  As of Jetty 9.4.8, HTTP/2 is also supported with the Conscrypt library.
To enable that support, your application needs to have two additional dependencies: and .

3.8.3. HTTP/2 with Tomcat

  Spring Boot ships by default with Tomcat 9.0.x which supports HTTP/2 out of the box when using JDK 9 or later.
Alternatively, HTTP/2 can be used on JDK 8 if the library and its dependencies are installed on the host operating system.

  The library folder must be made available, if not already, to the JVM library path.
You can do so with a JVM argument such as .
More on this in the official Tomcat documentation.

  Starting Tomcat 9.0.x on JDK 8 without that native support logs the following error:

  ERROR 8787 — [ main] o.a.coyote.http11.Http11NioProtocol : The upgrade handler [org.apache.coyote.http2.Http2Protocol] for [h2] only supports upgrade via ALPN but has been configured for the [“https-jsse-nio-8443”] connector that does not support ALPN.

  This error is not fatal, and the application still starts with HTTP/1.1 SSL support.

3.8.4. HTTP/2 with Reactor Netty

  The is using by default Reactor Netty as a server.
Reactor Netty can be configured for HTTP/2 using the JDK support with JDK 9 or later.
For JDK 8 environments, or for optimal runtime performance, this server also supports HTTP/2 with native libraries.
To enable that, your application needs to have an additional dependency.

  Spring Boot manages the version for the “uber jar”, containing native libraries for all platforms.
Developers can choose to import only the required dependencies using a classifier (see the Netty official documentation).

  3.9. Configure the Web Server

  Generally, you should first consider using one of the many available configuration keys and customize your web server by adding new entries in your (or , or environment, etc. see “Discover Built-in Options for External Properties”).
The namespace is quite useful here, and it includes namespaces like , and others, for server-specific features.
See the list of appendix-application-properties.html.

  The previous sections covered already many common use cases, such as compression, SSL or HTTP/2.
However, if a configuration key doesn’t exist for your use case, you should then look at .
You can declare such a component and get access to the server factory relevant to your choice: you should select the variant for the chosen Server (Tomcat, Jetty, Reactor Netty, Undertow) and the chosen web stack (Servlet or Reactive).

  The example below is for Tomcat with the (Servlet stack):

  In addition Spring Boot provides:

Server
Servlet stack
Reactive stack

  Tomcat

  Jetty

  Undertow

  Reactor

  N/A

  Once you’ve got access to a , you can often add customizers to it to configure specific parts, like connectors, server resources, or the server itself – all using server-specific APIs.

  As a last resort, you can also declare your own component, which will override the one provided by Spring Boot.
In this case, you can’t rely on configuration properties in the namespace anymore.

  3.10. Add a Servlet, Filter, or Listener to an Application

  In a servlet stack application, i.e. with the , there are two ways to add , , , and the other listeners supported by the Servlet API to your application:

  Add a Servlet, Filter, or Listener by Using a Spring Bean

  Add Servlets, Filters, and Listeners by Using Classpath Scanning

3.10.1. Add a Servlet, Filter, or Listener by Using a Spring Bean

  To add a , , or Servlet by using a Spring bean, you must provide a definition for it.
Doing so can be very useful when you want to inject configuration or dependencies.
However, you must be very careful that they do not cause eager initialization of too many other beans, because they have to be installed in the container very early in the application lifecycle.
(For example, it is not a good idea to have them depend on your or JPA configuration.)
You can work around such restrictions by initializing the beans lazily when first used instead of on initialization.

  In the case of and , you can also add mappings and init parameters by adding a or a instead of or in addition to the underlying component.

  If no is specified on a filter registration, is used.
This aligns with the Servlet Specification’s default dispatcher type.

  Like any other Spring bean, you can define the order of Servlet filter beans; please make sure to check the “spring-boot-features.html” section.

Disable Registration of a Servlet or Filter

  As described earlier, any or beans are registered with the servlet container automatically.
To disable registration of a particular or bean, create a registration bean for it and mark it as disabled, as shown in the following example:

  3.10.2. Add Servlets, Filters, and Listeners by Using Classpath Scanning

  , , and annotated classes can be automatically registered with an embedded servlet container by annotating a class with and specifying the package(s) containing the components that you want to register.
By default, scans from the package of the annotated class.

  3.11. Configure Access Logging

  Access logs can be configured for Tomcat, Undertow, and Jetty through their respective namespaces.

  For instance, the following settings log access on Tomcat with a custom pattern.

  The default location for logs is a directory relative to the Tomcat base directory.
By default, the directory is a temporary directory, so you may want to fix Tomcat’s base directory or use an absolute path for the logs.
In the preceding example, the logs are available in relative to the working directory of the application.

  Access logging for Undertow can be configured in a similar fashion, as shown in the following example:

  Logs are stored in a directory relative to the working directory of the application.
You can customize this location by setting the property.

  Finally, access logging for Jetty can also be configured as follows:

  By default, logs are redirected to .
For more details, see the Jetty documentation.

  3.12. Running Behind a Front-end Proxy Server

  Your application might need to send redirects or render content with absolute links back to itself.
When running behind a proxy, the caller wants a link to the proxy and not to the physical address of the machine hosting your app.
Typically, such situations are handled through a contract with the proxy, which adds headers to tell the back end how to construct links to itself.

  If the proxy adds conventional and headers (most proxy servers do so), the absolute links should be rendered correctly, provided is set to or in your .

If your application runs in Cloud Foundry or Heroku, the property defaults to .
In all other instances, it defaults to .

3.12.1. Customize Tomcat’s Proxy Configuration

  If you use Tomcat, you can additionally configure the names of the headers used to carry “forwarded” information, as shown in the following example:

  server.tomcat.remote-ip-header=x-your-remote-ip-header
server.tomcat.protocol-header=x-your-protocol-header

  Tomcat is also configured with a default regular expression that matches internal proxies that are to be trusted.
By default, IP addresses in , , and are trusted.
You can customize the valve’s configuration by adding an entry to , as shown in the following example:

  server.tomcat.internal-proxies=192\.168\.\d{1,3}\.\d{1,3}

The double backslashes are required only when you use a properties file for configuration.
If you use YAML, single backslashes are sufficient, and a value equivalent to that shown in the preceding example would be .

You can trust all proxies by setting the to empty (but do not do so in production).

  You can take complete control of the configuration of Tomcat’s by switching the automatic one off (to do so, set ) and adding a new valve instance in a bean.

  3.13. Enable Multiple Connectors with Tomcat

  You can add an to the , which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example:

  3.14. Use Tomcat’s LegacyCookieProcessor

  By default, the embedded Tomcat used by Spring Boot does not support “Version 0″ of the Cookie format, so you may see the following error:

  java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value

  If at all possible, you should consider updating your code to only store values compliant with later Cookie specifications.
If, however, you cannot change the way that cookies are written, you can instead configure Tomcat to use a .
To switch to the , use an bean that adds a , as shown in the following example:

  3.15. Enable Tomcat’s MBean Registry

  Embedded Tomcat’s MBean registry is disabled by default.
This minimizes Tomcat’s memory footprint.
If you want to use Tomcat’s MBeans, for example so that they can be used to expose metrics via Micrometer, you must use the property to do so, as shown in the following example:

  3.16. Enable Multiple Listeners with Undertow

  Add an to the and add a listener to the , as shown in the following example:

  3.17. Create WebSocket Endpoints Using @ServerEndpoint

  If you want to use in a Spring Boot application that used an embedded container, you must declare a single , as shown in the following example:

  The bean shown in the preceding example registers any annotated beans with the underlying WebSocket container.
When deployed to a standalone servlet container, this role is performed by a servlet container initializer, and the bean is not required.

  4. Spring MVC

  Spring Boot has a number of starters that include Spring MVC.
Note that some starters include a dependency on Spring MVC rather than include it directly.
This section answers common questions about Spring MVC and Spring Boot.

  4.1. Write a JSON REST Service

  Any Spring in a Spring Boot application should render JSON response by default as long as Jackson2 is on the classpath, as shown in the following example:

  As long as can be serialized by Jackson2 (true for a normal POJO or Groovy object), then serves a JSON representation of it by default.
Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML.

  4.2. Write an XML REST Service

  If you have the Jackson XML extension () on the classpath, you can use it to render XML responses.
The previous example that we used for JSON would work.
To use the Jackson XML renderer, add the following dependency to your project:

  If Jackson’s XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having annotated as , as shown in the following example:

  JAXB is only available out of the box with Java 8.
If you’re using a more recent Java generation, add the following dependency to your project:

  To get the server to render XML instead of JSON, you might have to send an header (or use a browser).

  4.3. Customize the Jackson ObjectMapper

  Spring MVC (client and server side) uses to negotiate content conversion in an HTTP exchange.
If Jackson is on the classpath, you already get the default converter(s) provided by , an instance of which is auto-configured for you.

  The (or for Jackson XML converter) instance (created by default) has the following customized properties:

  is disabled

  is disabled

  is disabled

  Spring Boot also has some features to make it easier to customize this behavior.

  You can configure the and instances by using the environment.
Jackson provides an extensive suite of simple on/off features that can be used to configure various aspects of its processing.
These features are described in six enums (in Jackson) that map onto properties in the environment:

Enum
Property
Values

  ,

  ,

  ,

  ,

  ,

  , , , ,

  For example, to enable pretty print, set .
Note that, thanks to the use of relaxed binding, the case of does not have to match the case of the corresponding enum constant, which is .

  This environment-based configuration is applied to the auto-configured bean and applies to any mappers created by using the builder, including the auto-configured bean.

  The context’s can be customized by one or more beans.
Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.

  Any beans of type are automatically registered with the auto-configured and are applied to any instances that it creates.
This provides a global mechanism for contributing custom modules when you add new features to your application.

  If you want to replace the default completely, either define a of that type and mark it as or, if you prefer the builder-based approach, define a .
Note that, in either case, doing so disables all auto-configuration of the .

  If you provide any of type , they replace the default value in the MVC configuration.
Also, a convenience bean of type is provided (and is always available if you use the default MVC configuration).
It has some useful methods to access the default and user-enhanced message converters.

  See the “Customize the @ResponseBody Rendering” section and the source code for more details.

  4.4. Customize the @ResponseBody Rendering

  Spring uses to render (or responses from ).
You can contribute additional converters by adding beans of the appropriate type in a Spring Boot context.
If a bean you add is of a type that would have been included by default anyway (such as for JSON conversions), it replaces the default value.
A convenience bean of type is provided and is always available if you use the default MVC configuration.
It has some useful methods to access the default and user-enhanced message converters (For example, it can be useful if you want to manually inject them into a custom ).

  As in normal MVC usage, any beans that you provide can also contribute converters by overriding the method.
However, unlike with normal MVC, you can supply only additional converters that you need (because Spring Boot uses the same mechanism to contribute its defaults).
Finally, if you opt out of the Spring Boot default MVC configuration by providing your own configuration, you can take control completely and do everything manually by using from .

  See the source code for more details.

  4.5. Handling Multipart File Uploads

  Spring Boot embraces the Servlet 3 API to support uploading files.
By default, Spring Boot configures Spring MVC with a maximum size of 1MB per file and a maximum of 10MB of file data in a single request.
You may override these values, the location to which intermediate data is stored (for example, to the directory), and the threshold past which data is flushed to disk by using the properties exposed in the class.
For example, if you want to specify that files be unlimited, set the property to .

  The multipart support is helpful when you want to receive multipart encoded file data as a -annotated parameter of type in a Spring MVC controller handler method.

  See the source for more details.

It is recommended to use the container’s built-in support for multipart uploads rather than introducing an additional dependency such as Apache Commons File Upload.

  4.6. Switch Off the Spring MVC DispatcherServlet

  By default, all content is served from the root of your application ().
If you would rather map to a different path, you can configure one as follows:

  If you have additional servlets you can declare a of type or for each and Spring Boot will register them transparently to the container.
Because servlets are registered that way, they can be mapped to a sub-context of the without invoking it.

  Configuring the yourself is unusual but if you really need to do it, a of type must be provided as well to provide the path of your custom .

  4.7. Switch off the Default MVC Configuration

  The easiest way to take complete control over MVC configuration is to provide your own with the annotation.
Doing so leaves all MVC configuration in your hands.

  4.8. Customize ViewResolvers

  A is a core component of Spring MVC, translating view names in to actual implementations.
Note that are mainly used in UI applications, rather than REST-style services (a is not used to render a ).
There are many implementations of to choose from, and Spring on its own is not opinionated about which ones you should use.
Spring Boot, on the other hand, installs one or two for you, depending on what it finds on the classpath and in the application context.
The uses all the resolvers it finds in the application context, trying each one in turn until it gets a result.
If you add your own, you have to be aware of the order and in which position your resolver is added.

  adds the following to your context:

  An named ‘defaultViewResolver’.
This one locates physical resources that can be rendered by using the (including static resources and JSP pages, if you use those).
It applies a prefix and a suffix to the view name and then looks for a physical resource with that path in the servlet context (the defaults are both empty but are accessible for external configuration through and ).
You can override it by providing a bean of the same type.

  A named ‘beanNameViewResolver’.
This is a useful member of the view resolver chain and picks up any beans with the same name as the being resolved.
It should not be necessary to override or replace it.

  A named ‘viewResolver’ is added only if there are actually beans of type present.
This is a ‘master’ resolver, delegating to all the others and attempting to find a match to the ‘Accept’ HTTP header sent by the client.
There is a useful blog about that you might like to study to learn more, and you might also look at the source code for detail.
You can switch off the auto-configured by defining a bean named ‘viewResolver’.

  If you use Thymeleaf, you also have a named ‘thymeleafViewResolver’.
It looks for resources by surrounding the view name with a prefix and suffix.
The prefix is , and the suffix is .
The values of the prefix and suffix default to ‘classpath:/templates/’ and ‘.html’, respectively.
You can override by providing a bean of the same name.

  If you use FreeMarker, you also have a named ‘freeMarkerViewResolver’.
It looks for resources in a loader path (which is externalized to and has a default value of ‘classpath:/templates/’) by surrounding the view name with a prefix and a suffix.
The prefix is externalized to , and the suffix is externalized to .
The default values of the prefix and suffix are empty and ‘.ftlh’, respectively.
You can override by providing a bean of the same name.

  If you use Groovy templates (actually, if is on your classpath), you also have a named ‘groovyMarkupViewResolver’.
It looks for resources in a loader path by surrounding the view name with a prefix and suffix (externalized to and ).
The prefix and suffix have default values of ‘classpath:/templates/’ and ‘.tpl’, respectively.
You can override by providing a bean of the same name.

  If you use Mustache, you also have a named ‘mustacheViewResolver’.
It looks for resources by surrounding the view name with a prefix and suffix.
The prefix is , and the suffix is .
The values of the prefix and suffix default to ‘classpath:/templates/’ and ‘.mustache’, respectively.
You can override by providing a bean of the same name.

  For more detail, see the following sections:

  5. Testing With Spring Security

  Spring Security provides support for running tests as a specific user.
For example, the test in the snippet below will run with an authenticated user that has the role.

  Spring Security provides comprehensive integration with Spring MVC Test and this can also be used when testing controllers using the slice and .

  For additional details on Spring Security’s testing support, refer to Spring Security’s reference documentation).

  6. Jersey

  6.1. Secure Jersey endpoints with Spring Security

  Spring Security can be used to secure a Jersey-based web application in much the same way as it can be used to secure a Spring MVC-based web application.
However, if you want to use Spring Security’s method-level security with Jersey, you must configure Jersey to use rather .
This prevents Jersey from committing the response before Spring Security has had an opportunity to report an authentication or authorization failure to the client.

  The property must be set to on the application’s bean, as shown in the following example:

  6.2. Use Jersey Alongside Another Web Framework

  To use Jersey alongside another web framework, such as Spring MVC, it should be configured so that it will allow the other framework to handle requests that it cannot handle.
First, configure Jersey to use a Filter rather than a Servlet by configuring the application property with a value of .
Second, configure your to forward requests that would have resulted in a 404, as shown in the following example.

  7. HTTP Clients

  Spring Boot offers a number of starters that work with HTTP clients.
This section answers questions related to using them.

  7.1. Configure RestTemplate to Use a Proxy

  As described in spring-boot-features.html, you can use a with to build a customized .
This is the recommended approach for creating a configured to use a proxy.

  The exact details of the proxy configuration depend on the underlying client request factory that is being used.
The following example configures with an that uses a proxy for all hosts except :

  7.2. Configure the TcpClient used by a Reactor Netty-based WebClient

  When Reactor Netty is on the classpath a Reactor Netty-based is auto-configured.
To customize the client’s handling of network connections, provide a bean.
The following example configures a 60 second connect timeout and adds a :

  Note the use of for the connection provider and event loop resources.
This ensures efficient sharing of resources for the server receiving requests and the client making requests.

  8. Logging

  Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s module.
To use Logback, you need to include it and on the classpath.
The simplest way to do that is through the starters, which all depend on .
For a web application, you need only , since it depends transitively on the logging starter.
If you use Maven, the following dependency adds logging for you:

  Spring Boot has a abstraction that attempts to configure logging based on the content of the classpath.
If Logback is available, it is the first choice.

  If the only change you need to make to logging is to set the levels of various loggers, you can do so in by using the “logging.level” prefix, as shown in the following example:

  You can also set the location of a file to which to write the log (in addition to the console) by using “logging.file.name”.

  To configure the more fine-grained settings of a logging system, you need to use the native configuration format supported by the in question.
By default, Spring Boot picks up the native configuration from its default location for the system (such as for Logback), but you can set the location of the config file by using the property.

  8.1. Configure Logback for Logging

  If you need to apply customizations to logback beyond those that can be achieved with , you’ll need to add a standard logback configuration file.
You can add a file to the root of your classpath for logback to find.
You can also use if you want to use the Spring Boot Logback extensions.

The Logback documentation has a dedicated section that covers configuration in some detail.

  Spring Boot provides a number of logback configurations that be from your own configuration.
These includes are designed to allow certain common Spring Boot conventions to be re-applied.

  The following files are provided under :

  - Provides conversion rules, pattern properties and common logger configurations.

  - Adds a using the .

  - Adds a using the and with appropriate settings.

  In addition, a legacy file is provided for compatibility with earlier versions of Spring Boot.

  A typical custom file would look something like this:

  Your logback configuration file can also make use of System properties that the takes care of creating for you:

  : The current process ID.

  : Whether was set in Boot’s external configuration.

  : Whether (representing a directory for log files to live in) was set in Boot’s external configuration.

  : Whether was set in Boot’s external configuration.

  : Whether was set in Boot’s external configuration.

  Spring Boot also provides some nice ANSI color terminal output on a console (but not in a log file) by using a custom Logback converter.
See the in the configuration for an example.

  If Groovy is on the classpath, you should be able to configure Logback with as well.
If present, this setting is given preference.

Spring extensions are not supported with Groovy configuration.
Any files will not be detected.

8.1.1. Configure Logback for File-only Output

  If you want to disable console logging and write output only to a file, you need a custom that imports but not , as shown in the following example:

  You also need to add to your , as shown in the following example:

  8.2. Configure Log4j for Logging

  Spring Boot supports Log4j 2 for logging configuration if it is on the classpath.
If you use the starters for assembling dependencies, you have to exclude Logback and then include log4j 2 instead.
If you do not use the starters, you need to provide (at least) in addition to Log4j 2.

  The simplest path is probably through the starters, even though it requires some jiggling with excludes.
The following example shows how to set up the starters in Maven:

  And the following example shows one way to set up the starters in Gradle:

  The Log4j starters gather together the dependencies for common logging requirements (such as having Tomcat use but configuring the output using Log4j 2).

To ensure that debug logging performed using is routed into Log4j 2, configure its JDK logging adapter by setting the system property to .

8.2.1. Use YAML or JSON to Configure Log4j 2

  In addition to its default XML configuration format, Log4j 2 also supports YAML and JSON configuration files.
To configure Log4j 2 to use an alternative configuration file format, add the appropriate dependencies to the classpath and name your configuration files to match your chosen file format, as shown in the following example:

Format
Dependencies
File names

  YAML

  +

  +

  JSON

  +

  9. Data Access

  Spring Boot includes a number of starters for working with data sources.
This section answers questions related to doing so.

  9.1. Configure a Custom DataSource

  To configure your own , define a of that type in your configuration.
Spring Boot reuses your anywhere one is required, including database initialization.
If you need to externalize some settings, you can bind your to the environment (see “spring-boot-features.html”).

  The following example shows how to define a data source in a bean:

  The following example shows how to define a data source by setting properties:

  Assuming that your has regular JavaBean properties for the URL, the username, and the pool size, these settings are bound automatically before the is made available to other components.
The regular database initialization also happens (so the relevant sub-set of can still be used with your custom configuration).

  Spring Boot also provides a utility builder class, called , that can be used to create one of the standard data sources (if it is on the classpath).
The builder can detect the one to use based on what’s available on the classpath.
It also auto-detects the driver based on the JDBC URL.

  The following example shows how to create a data source by using a :

  To run an app with that , all you need is the connection information.
Pool-specific settings can also be provided.
Check the implementation that is going to be used at runtime for more details.

  The following example shows how to define a JDBC data source by setting properties:

  However, there is a catch.
Because the actual type of the connection pool is not exposed, no keys are generated in the metadata for your custom and no completion is available in your IDE (because the interface exposes no properties).
Also, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no property (but does have a property).
In that case, you must rewrite your configuration as follows:

  You can fix that by forcing the connection pool to use and return a dedicated implementation rather than .
You cannot change the implementation at runtime, but the list of options will be explicit.

  The following example shows how create a with :

  You can even go further by leveraging what does for you — that is, by providing a default embedded database with a sensible username and password if no URL is provided.
You can easily initialize a from the state of any object, so you could also inject the DataSource that Spring Boot creates automatically.
However, that would split your configuration into two namespaces: , , , , and on and the rest on your custom namespace ().
To avoid that, you can redefine a custom on your custom namespace, as shown in the following example:

  This setup puts you in sync with what Spring Boot does for you by default, except that a dedicated connection pool is chosen (in code) and its settings are exposed in the sub namespace.
Because is taking care of the / translation for you, you can configure it as follows:

  Spring Boot will expose Hikari-specific settings to .
This example uses a more generic sub namespace as the example does not support multiple datasource implementations.

Because your custom configuration chooses to go with Hikari, has no effect.
In practice, the builder is initialized with whatever value you might set there and then overridden by the call to .

  See “spring-boot-features.html” in the “Spring Boot features” section and the class for more details.

  9.2. Configure Two DataSources

  If you need to configure multiple data sources, you can apply the same tricks that are described in the previous section.
You must, however, mark one of the instances as , because various auto-configurations down the road expect to be able to get one by type.

  If you create your own , the auto-configuration backs off.
In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

  has to be flagged as so that the database initializer feature uses your copy (if you use the initializer).

  Both data sources are also bound for advanced customizations.
For instance, you could configure them as follows:

  You can apply the same concept to the secondary as well, as shown in the following example:

  The preceding example configures two data sources on custom namespaces with the same logic as Spring Boot would use in auto-configuration.
Note that each sub namespace provides advanced settings based on the chosen implementation.

  9.3. Use Spring Data Repositories

  Spring Data can create implementations of interfaces of various flavors.
Spring Boot handles all of that for you, as long as those are included in the same package (or a sub-package) of your class.

  For many applications, all you need is to put the right Spring Data dependencies on your classpath.
There is a for JPA, spring-boot-starter-data-mongodb` for Mongodb, etc.
To get started, create some repository interfaces to handle your objects.

  Spring Boot tries to guess the location of your definitions, based on the it finds.
To get more control, use the annotation (from Spring Data JPA).

  For more about Spring Data, see the Spring Data project page.

  9.4. Separate @Entity Definitions from Spring Configuration

  Spring Boot tries to guess the location of your definitions, based on the it finds.
To get more control, you can use the annotation, as shown in the following example:

  9.5. Configure JPA Properties

  Spring Data JPA already provides some vendor-independent configuration options (such as those for SQL logging), and Spring Boot exposes those options and a few more for Hibernate as external configuration properties.
Some of them are automatically detected according to the context so you should not have to set them.

  The is a special case, because, depending on runtime conditions, it has different defaults.
If an embedded database is used and no schema manager (such as Liquibase or Flyway) is handling the , it defaults to .
In all other cases, it defaults to .

  The dialect to use is detected by the JPA provider.
If you prefer to set the dialect yourself, set the property.

  The most common options to set are shown in the following example:

  spring.jpa.hibernate.naming.physical-strategy=com.example.MyPhysicalNamingStrategy
spring.jpa.show-sql=true

  In addition, all properties in are passed through as normal JPA properties (with the prefix stripped) when the local is created.

  You need to ensure that names defined under exactly match those expected by your JPA provider.
Spring Boot will not attempt any kind of relaxed binding for these entries.

  For example, if you want to configure Hibernate’s batch size you must use .
If you use other forms, such as or , Hibernate will not apply the setting.

If you need to apply advanced customization to Hibernate properties, consider registering a bean that will be invoked prior to creating the .
This takes precedence to anything that is applied by the auto-configuration.

  9.6. Configure Hibernate Naming Strategy

  Hibernate uses two different naming strategies to map names from the object model to the corresponding database names.
The fully qualified class name of the physical and the implicit strategy implementations can be configured by setting the and properties, respectively.
Alternatively, if or beans are available in the application context, Hibernate will be automatically configured to use them.

  By default, Spring Boot configures the physical naming strategy with .
This implementation provides the same table structure as Hibernate 4: all dots are replaced by underscores and camel casing is replaced by underscores as well.
By default, all table names are generated in lower case, but it is possible to override that flag if your schema requires it.

  For example, a entity is mapped to the table.

  If you prefer to use Hibernate 5’s default instead, set the following property:

  spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

  Alternatively, you can configure the following bean:

  See and for more details.

  9.7. Configure Hibernate Second-Level Caching

  Hibernate second-level cache can be configured for a range of cache providers.
Rather than configuring Hibernate to lookup the cache provider again, it is better to provide the one that is available in the context whenever possible.

  If you’re using JCache, this is pretty easy.
First, make sure that is available on the classpath.
Then, add a bean as shown in the following example:

  This customizer will configure Hibernate to use the same as the one that the application uses.
It is also possible to use separate instances.
For details, refer to the Hibernate user guide.

  9.8. Use Dependency Injection in Hibernate Components

  By default, Spring Boot registers a implementation that uses the so that converters and entity listeners can use regular dependency injection.

  You can disable or tune this behaviour by registering a that removes or changes the property.

  9.9. Use a Custom EntityManagerFactory

  To take full control of the configuration of the , you need to add a named ‘entityManagerFactory’.
Spring Boot auto-configuration switches off its entity manager in the presence of a bean of that type.

  9.10. Use Two EntityManagers

  Even if the default works fine, you need to define a new one.
Otherwise, the presence of the second bean of that type switches off the default.
To make it easy to do, you can use the convenient provided by Spring Boot.
Alternatively, you can just the directly from Spring ORM, as shown in the following example:

  When you create a bean for yourself, any customization that was applied during the creation of the auto-configured is lost.
For example, in case of Hibernate, any properties under the prefix will not be automatically applied to your .
If you were relying on these properties for configuring things like the naming strategy or the DDL mode, you will need to explicitly configure that when creating the bean.
On the other hand, properties that get applied to the auto-configured , which are specified via , will automatically be applied, provided you use the auto-configured to build the bean.

  The configuration above almost works on its own.
To complete the picture, you need to configure for the two as well.
If you mark one of them as , it could be picked up by the default in Spring Boot.
The other would have to be explicitly injected into a new instance.
Alternatively, you might be able to use a JTA transaction manager that spans both.

  If you use Spring Data, you need to configure accordingly, as shown in the following example:

  9.11. Use a Traditional File

  Spring Boot will not search for or use a by default.
If you prefer to use a traditional , you need to define your own of type (with an ID of ‘entityManagerFactory’) and set the persistence unit name there.

  See for the default settings.

  9.12. Use Spring Data JPA and Mongo Repositories

  Spring Data JPA and Spring Data Mongo can both automatically create implementations for you.
If they are both present on the classpath, you might have to do some extra configuration to tell Spring Boot which repositories to create.
The most explicit way to do that is to use the standard Spring Data and annotations and provide the location of your interfaces.

  There are also flags ( and ) that you can use to switch the auto-configured repositories on and off in external configuration.
Doing so is useful, for instance, in case you want to switch off the Mongo repositories and still use the auto-configured .

  The same obstacle and the same features exist for other auto-configured Spring Data repository types (Elasticsearch, Solr, and others).
To work with them, change the names of the annotations and flags accordingly.

  9.13. Customize Spring Data’s Web Support

  Spring Data provides web support that simplifies the use of Spring Data repositories in a web application.
Spring Boot provides properties in the namespace for customizing its configuration.
Note that if you are using Spring Data REST, you must use the properties in the namespace instead.

  9.14. Expose Spring Data Repositories as REST Endpoint

  Spring Data REST can expose the implementations as REST endpoints for you,
provided Spring MVC has been enabled for the application.

  Spring Boot exposes a set of useful properties (from the namespace) that customize the .
If you need to provide additional customization, you should use a bean.

If you do not specify any order on your custom , it runs after the one Spring Boot uses internally.
If you need to specify an order, make sure it is higher than 0.

  9.15. Configure a Component that is Used by JPA

  If you want to configure a component that JPA uses, then you need to ensure that the component is initialized before JPA.
When the component is auto-configured, Spring Boot takes care of this for you.
For example, when Flyway is auto-configured, Hibernate is configured to depend upon Flyway so that Flyway has a chance to initialize the database before Hibernate tries to use it.

  If you are configuring a component yourself, you can use an subclass as a convenient way of setting up the necessary dependencies.
For example, if you use Hibernate Search with Elasticsearch as its index manager, any beans must be configured to depend on the bean, as shown in the following example:

  9.16. Configure jOOQ with Two DataSources

  If you need to use jOOQ with multiple data sources, you should create your own for each one.
Refer to JooqAutoConfiguration for more details.

In particular, and can be reused to provide similar features to what the auto-configuration does with a single .

  10. Database Initialization

  An SQL database can be initialized in different ways depending on what your stack is.
Of course, you can also do it manually, provided the database is a separate process.
It is recommended to use a single mechanism for schema generation.

  10.1. Initialize a Database Using JPA

  JPA has features for DDL generation, and these can be set up to run on startup against the database.
This is controlled through two external properties:

  (boolean) switches the feature on and off and is vendor independent.

  (enum) is a Hibernate feature that controls the behavior in a more fine-grained way.
This feature is described in more detail later in this guide.

  10.2. Initialize a Database Using Hibernate

  You can set explicitly and the standard Hibernate property values are , , , , and .
Spring Boot chooses a default value for you based on whether it thinks your database is embedded.
It defaults to if no schema manager has been detected or in all other cases.
An embedded database is detected by looking at the type.
, , and are embedded, and others are not.
Be careful when switching from in-memory to a ‘real’ database that you do not make assumptions about the existence of the tables and data in the new platform.
You either have to set explicitly or use one of the other mechanisms to initialize the database.

You can output the schema creation by enabling the logger.
This is done for you automatically if you enable the debug mode.

  In addition, a file named in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the property is set to or ).
This can be useful for demos and for testing if you are careful but is probably not something you want to be on the classpath in production.
It is a Hibernate feature (and has nothing to do with Spring).

  10.3. Initialize a Database

  Spring Boot can automatically create the schema (DDL scripts) of your and initialize it (DML scripts).
It loads SQL from the standard root classpath locations: and , respectively.
In addition, Spring Boot processes the and files (if present), where is the value of .
This allows you to switch to database-specific scripts if necessary.
For example, you might choose to set it to the vendor name of the database (, , , , , and so on).

  Spring Boot automatically creates the schema of an embedded .
This behavior can be customized by using the property.
For instance, if you want to always initialize the regardless of its type:

  spring.datasource.initialization-mode=always

  By default, Spring Boot enables the fail-fast feature of the Spring JDBC initializer.
This means that, if the scripts cause exceptions, the application fails to start.
You can tune that behavior by setting .

In a JPA-based app, you can choose to let Hibernate create the schema or use , but you cannot do both.
Make sure to disable if you use .

  10.4. Initialize a Spring Batch Database

  If you use Spring Batch, it comes pre-packaged with SQL initialization scripts for most popular database platforms.
Spring Boot can detect your database type and execute those scripts on startup.
If you use an embedded database, this happens by default.
You can also enable it for any database type, as shown in the following example:

  spring.batch.initialize-schema=always

  You can also switch off the initialization explicitly by setting .

  10.5. Use a Higher-level Database Migration Tool

  Spring Boot supports two higher-level migration tools: Flyway and Liquibase.

10.5.1. Execute Flyway Database Migrations on Startup

  To automatically run Flyway database migrations on startup, add the to your classpath.

  Typically, migrations are scripts in the form (with an underscore-separated version, such as ‘1’ or ‘2_1’).
By default, they are in a folder called , but you can modify that location by setting .
This is a comma-separated list of one or more or locations.
For example, the following configuration would search for scripts in both the default classpath location and the directory:

  You can also add a special placeholder to use vendor-specific scripts.
Assume the following:

  Rather than using , the preceding configuration sets the folder to use according to the type of the database (such as for MySQL).
The list of supported databases is available in .

  Migrations can also be written in Java.
Flyway will be auto-configured with any beans that implement .

  provides most of Flyway’s settings and a small set of additional properties that can be used to disable the migrations or switch off the location checking.
If you need more control over the configuration, consider registering a bean.

  Spring Boot calls to perform the database migration.
If you would like more control, provide a that implements .

  Flyway supports SQL and Java callbacks.
To use SQL-based callbacks, place the callback scripts in the folder.
To use Java-based callbacks, create one or more beans that implement .
Any such beans are automatically registered with .
They can be ordered by using or by implementing .
Beans that implement the deprecated interface can also be detected, however they cannot be used alongside beans.

  By default, Flyway autowires the () in your context and uses that for migrations.
If you like to use a different , you can create one and mark its as .
If you do so and want two data sources, remember to create another one and mark it as .
Alternatively, you can use Flyway’s native by setting in external properties.
Setting either or is sufficient to cause Flyway to use its own .
If any of the three properties has not be set, the value of its equivalent property will be used.

  You can also use Flyway to provide data for specific scenarios.
For example, you can place test-specific migrations in and they are run only when your application starts for testing.
Also, you can use profile-specific configuration to customize so that certain migrations run only when a particular profile is active.
For example, in , you might specify the following setting:

  With that setup, migrations in run only when the profile is active.

10.5.2. Execute Liquibase Database Migrations on Startup

  To automatically run Liquibase database migrations on startup, add the to your classpath.

  By default, the master change log is read from , but you can change the location by setting .
In addition to YAML, Liquibase also supports JSON, XML, and SQL change log formats.

  By default, Liquibase autowires the () in your context and uses that for migrations.
If you need to use a different , you can create one and mark its as .
If you do so and you want two data sources, remember to create another one and mark it as .
Alternatively, you can use Liquibase’s native by setting in external properties.
Setting either or is sufficient to cause Liquibase to use its own .
If any of the three properties has not be set, the value of its equivalent property will be used.

  See for details about available settings such as contexts, the default schema, and others.

  11. Messaging

  Spring Boot offers a number of starters that include messaging.
This section answers questions that arise from using messaging with Spring Boot.

  11.1. Disable Transacted JMS Session

  If your JMS broker does not support transacted sessions, you have to disable the support of transactions altogether.
If you create your own , there is nothing to do, since, by default it cannot be transacted.
If you want to use the to reuse Spring Boot’s default, you can disable transacted sessions, as follows:

  The preceding example overrides the default factory, and it should be applied to any other factory that your application defines, if any.

  12. Batch Applications

  This section answers questions that arise from using Spring Batch with Spring Boot.

By default, batch applications require a to store job details.
Batch autowires a single in your context and uses that for processing.
To have Batch use a other than the application’s main , declare a bean, annotating its method with .
If you do so and want two data sources, remember to create another one and mark it as .
To take greater control, implement .
See The Javadoc of for more details.

  For more about Spring Batch, see the Spring Batch project page.

  12.1. Execute Spring Batch Jobs on Startup

  Spring Batch auto-configuration is enabled by adding (from Spring Batch) somewhere in your context.

  By default, it executes all in the application context on startup (see JobLauncherCommandLineRunner for details).
You can narrow down to a specific job or jobs by specifying (which takes a comma-separated list of job name patterns).

Specifying job parameters on the command line

  Unlike command line option arguments that set properties in the (i.e. by starting with , such as ), job parameters have to be specified on the command line without dashes (e.g. ).

  If the application context includes a , the jobs in are looked up in the registry instead of being autowired from the context.
This is a common pattern with more complex systems, where multiple jobs are defined in child contexts and registered centrally.

  See BatchAutoConfiguration and @EnableBatchProcessing for more details.

  13. Actuator

  Spring Boot includes the Spring Boot Actuator.
This section answers questions that often arise from its use.

  13.1. Change the HTTP Port or Address of the Actuator Endpoints

  In a standalone application, the Actuator HTTP port defaults to the same as the main HTTP port.
To make the application listen on a different port, set the external property: .
To listen on a completely different network address (such as when you have an internal network for management and an external one for user applications), you can also set to a valid IP address to which the server is able to bind.

  For more detail, see the source code and “production-ready-features.html” in the “Production-ready features” section.

  13.2. Customize the ‘whitelabel’ Error Page

  Spring Boot installs a ‘whitelabel’ error page that you see in a browser client if you encounter a server error (machine clients consuming JSON and other media types should see a sensible response with the right error code).

Set to switch the default error page off.
Doing so restores the default of the servlet container that you are using.
Note that Spring Boot still tries to resolve the error view, so you should probably add your own error page rather than disabling it completely.

  Overriding the error page with your own depends on the templating technology that you use.
For example, if you use Thymeleaf, you can add an template.
If you use FreeMarker, you can add an template.
In general, you need a that resolves with a name of or a that handles the path.
Unless you replaced some of the default configuration, you should find a in your , so a named would be a simple way of doing that.
See for more options.

  See also the section on “Error Handling” for details of how to register handlers in the servlet container.

  13.3. Sanitize sensible values

  Information returned by the and endpoints can be somewhat sensitive so keys matching a certain pattern are sanitized by default (i.e. their values are replaced by ).

  Spring Boot uses sensible defaults for such keys: for instance, any key ending with the word “password”, “secret”, “key” or “token” is sanitized.
It is also possible to use a regular expression instead, such as to sanitize any key that holds the word as part of the key.

  The patterns to use can be customized using the and respectively.

  14. Security

  This section addresses questions about security when working with Spring Boot, including questions that arise from using Spring Security with Spring Boot.

  For more about Spring Security, see the Spring Security project page.

  14.1. Switch off the Spring Boot Security Configuration

  If you define a with a in your application, it switches off the default webapp security settings in Spring Boot.

  14.2. Change the UserDetailsService and Add User Accounts

  If you provide a of type , , or , the default for is not created.
This means you have the full feature set of Spring Security available (such as various authentication options).

  The easiest way to add user accounts is to provide your own bean.

  14.3. Enable HTTPS When Running behind a Proxy Server

  Ensuring that all your main endpoints are only available over HTTPS is an important chore for any application.
If you use Tomcat as a servlet container, then Spring Boot adds Tomcat’s own automatically if it detects some environment settings, and you should be able to rely on the to report whether it is secure or not (even downstream of a proxy server that handles the real SSL termination).
The standard behavior is determined by the presence or absence of certain request headers ( and ), whose names are conventional, so it should work with most front-end proxies.
You can switch on the valve by adding some entries to , as shown in the following example:

  (The presence of either of those properties switches on the valve.
Alternatively, you can add the by adding a bean.)

  To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own that adds the following configuration:

  15. Hot Swapping

  Spring Boot supports hot swapping.
This section answers questions about how it works.

  15.1. Reload Static Content

  There are several options for hot reloading.
The recommended approach is to use , as it provides additional development-time features, such as support for fast application restarts and LiveReload as well as sensible development-time configuration (such as template caching).
Devtools works by monitoring the classpath for changes.
This means that static resource changes must be “built” for the change to take effect.
By default, this happens automatically in Eclipse when you save your changes.
In IntelliJ IDEA, the Make Project command triggers the necessary build.
Due to the default restart exclusions, changes to static resources do not trigger a restart of your application.
They do, however, trigger a live reload.

  Alternatively, running in an IDE (especially with debugging on) is a good way to do development (all modern IDEs allow reloading of static resources and usually also allow hot-swapping of Java class changes).

  Finally, the Maven and Gradle plugins can be configured (see the property) to support running from the command line with reloading of static files directly from source.
You can use that with an external css/js compiler process if you are writing that code with higher-level tools.

  15.2. Reload Templates without Restarting the Container

  Most of the templating technologies supported by Spring Boot include a configuration option to disable caching (described later in this document).
If you use the module, these properties are automatically configured for you at development time.

15.2.1. Thymeleaf Templates

  If you use Thymeleaf, set to .
See for other Thymeleaf customization options.

15.2.2. FreeMarker Templates

  If you use FreeMarker, set to .
See for other FreeMarker customization options.

15.2.3. Groovy Templates

  If you use Groovy templates, set to .
See for other Groovy customization options.

  15.3. Fast Application Restarts

  The module includes support for automatic application restarts.
While not as fast as technologies such as JRebel it is usually significantly faster than a “cold start”.
You should probably give it a try before investigating some of the more complex reload options discussed later in this document.

  For more details, see the using-spring-boot.html section.

  15.4. Reload Java Classes without Restarting the Container

  Many modern IDEs (Eclipse, IDEA, and others) support hot swapping of bytecode.
Consequently, if you make a change that does not affect class or method signatures, it should reload cleanly with no side effects.

  16. Build

  Spring Boot includes build plugins for Maven and Gradle.
This section answers common questions about these plugins.

  16.1. Generate Build Information

  Both the Maven plugin and the Gradle plugin allow generating build information containing the coordinates, name, and version of the project.
The plugins can also be configured to add additional properties through configuration.
When such a file is present, Spring Boot auto-configures a bean.

  To generate build information with Maven, add an execution for the goal, as shown in the following example:

  See the Spring Boot Maven Plugin documentation for more details.

  The following example does the same with Gradle:

  See the Spring Boot Gradle Plugin documentation for more details.

  16.2. Generate Git Information

  Both Maven and Gradle allow generating a file containing information about the state of your source code repository when the project was built.

  For Maven users, the POM includes a pre-configured plugin to generate a file.
To use it, add the following declaration to your POM:

  Gradle users can achieve the same result by using the plugin, as shown in the following example:

  The commit time in is expected to match the following format: .
This is the default format for both plugins listed above.
Using this format lets the time be parsed into a and its format, when serialized to JSON, to be controlled by Jackson’s date serialization configuration settings.

  16.3. Customize Dependency Versions

  If you use a Maven build that inherits directly or indirectly from (for instance, ) but you want to override a specific third-party dependency, you can add appropriate elements.
Browse the POM for a complete list of properties.
For example, to pick a different version, you would add the following property:

  Doing so only works if your Maven project inherits (directly or indirectly) from .
If you have added in your own section with , you have to redefine the artifact yourself instead of overriding the property.

Each Spring Boot release is designed and tested against this specific set of third-party dependencies.
Overriding versions may cause compatibility issues.

  To override dependency versions in Gradle, see this section of the Gradle plugin’s documentation.

  16.4. Create an Executable JAR with Maven

  The can be used to create an executable “fat” JAR.
If you use the POM, you can declare the plugin and your jars are repackaged as follows:

  If you do not use the parent POM, you can still use the plugin.
However, you must additionally add an section, as follows:

  See the plugin documentation for full usage details.

  16.5. Use a Spring Boot Application as a Dependency

  Like a war file, a Spring Boot application is not intended to be used as a dependency.
If your application contains classes that you want to share with other projects, the recommended approach is to move that code into a separate module.
The separate module can then be depended upon by your application and other projects.

  If you cannot rearrange your code as recommended above, Spring Boot’s Maven and Gradle plugins must be configured to produce a separate artifact that is suitable for use as a dependency.
The executable archive cannot be used as a dependency as the executable jar format packages application classes in .
This means that they cannot be found when the executable jar is used as a dependency.

  To produce the two artifacts, one that can be used as a dependency and one that is executable, a classifier must be specified.
This classifier is applied to the name of the executable archive, leaving the default archive for use as a dependency.

  To configure a classifier of in Maven, you can use the following configuration:

  16.6. Extract Specific Libraries When an Executable Jar Runs

  Most nested libraries in an executable jar do not need to be unpacked in order to run.
However, certain libraries can have problems.
For example, JRuby includes its own nested jar support, which assumes that the is always directly available as a file in its own right.

  To deal with any problematic libraries, you can flag that specific nested jars should be automatically unpacked when the executable jar first runs.
Such nested jars are written beneath the temporary directory identified by the system property.

Care should be taken to ensure that your operating system is configured so that it will not delete the jars that have been unpacked to the temporary directory while the application is still running.

  For example, to indicate that JRuby should be flagged for unpacking by using the Maven Plugin, you would add the following configuration:

  16.7. Create a Non-executable JAR with Exclusions

  Often, if you have an executable and a non-executable jar as two separate build products, the executable version has additional configuration files that are not needed in a library jar.
For example, the configuration file might by excluded from the non-executable JAR.

  In Maven, the executable jar must be the main artifact and you can add a classified jar for the library, as follows:

  16.8. Remote Debug a Spring Boot Application Started with Maven

  To attach a remote debugger to a Spring Boot application that was started with Maven, you can use the property of the maven plugin.

  See this example for more details.

  16.9. Build an Executable Archive from Ant without Using

  To build with Ant, you need to grab dependencies, compile, and then create a jar or war archive.
To make it executable, you can either use the module or you can follow these instructions:

  If you are building a jar, package the application’s classes and resources in a nested directory.
If you are building a war, package the application’s classes in a nested directory as usual.

  Add the runtime dependencies in a nested directory for a jar or for a war.
Remember not to compress the entries in the archive.

  Add the (embedded container) dependencies in a nested directory for a jar or for a war.
Remember not to compress the entries in the archive.

  Add the classes at the root of the archive (so that the is available).

  Use the appropriate launcher (such as for a jar file) as a attribute in the manifest and specify the other properties it needs as manifest entries — principally, by setting a property.

  The following example shows how to build an executable archive with Ant:

  17. Traditional Deployment

  Spring Boot supports traditional deployment as well as more modern forms of deployment.
This section answers common questions about traditional deployment.

  17.1. Create a Deployable War File

  Because Spring WebFlux does not strictly depend on the Servlet API and applications are deployed by default on an embedded Reactor Netty server, War deployment is not supported for WebFlux applications.

  The first step in producing a deployable war file is to provide a subclass and override its method.
Doing so makes use of Spring Framework’s Servlet 3.0 support and lets you configure your application when it is launched by the servlet container.
Typically, you should update your application’s main class to extend , as shown in the following example:

  The next step is to update your build configuration such that your project produces a war file rather than a jar file.
If you use Maven and (which configures Maven’s war plugin for you), all you need to do is to modify to change the packaging to war, as follows:

  If you use Gradle, you need to modify to apply the war plugin to the project, as follows:

  The final step in the process is to ensure that the embedded servlet container does not interfere with the servlet container to which the war file is deployed.
To do so, you need to mark the embedded servlet container dependency as being provided.

  If you use Maven, the following example marks the servlet container (Tomcat, in this case) as being provided:

  If you use Gradle, the following example marks the servlet container (Tomcat, in this case) as being provided:

  is preferred to Gradle’s configuration.
Among other limitations, dependencies are not on the test classpath, so any web-based integration tests fail.

  If you use the Spring Boot build tools, marking the embedded servlet container dependency as provided produces an executable war file with the provided dependencies packaged in a directory.
This means that, in addition to being deployable to a servlet container, you can also run your application by using on the command line.

  17.2. Convert an Existing Application to Spring Boot

  For a non-web application, it should be easy to convert an existing Spring application to a Spring Boot application.
To do so, throw away the code that creates your and replace it with calls to or .
Spring MVC web applications are generally amenable to first creating a deployable war application and then migrating it later to an executable war or jar.
See the Getting Started Guide on Converting a jar to a war.

  To create a deployable war by extending (for example, in a class called ) and adding the Spring Boot annotation, use code similar to that shown in the following example:

  Remember that, whatever you put in the is merely a Spring .
Normally, anything that already works should work here.
There might be some beans you can remove later and let Spring Boot provide its own defaults for them, but it should be possible to get something working before you need to do that.

  Static resources can be moved to (or or or ) in the classpath root.
The same applies to (which Spring Boot automatically detects in the root of the classpath).

  Vanilla usage of Spring and Spring Security should require no further changes.
If you have other features in your application (for instance, using other servlets or filters), you may need to add some configuration to your context, by replacing those elements from the , as follows:

  A of type or installs that bean in the container as if it were a and in .

  A of type or behaves similarly (as a and ).

  An in an XML file can be added through an in your .
Alternatively, simple cases where annotation configuration is heavily used already can be recreated in a few lines as definitions.

  Once the war file is working, you can make it executable by adding a method to your , as shown in the following example:

  If you intend to start your application as a war or as an executable application, you need to share the customizations of the builder in a method that is both available to the callback and in the method in a class similar to the following:

  Applications can fall into more than one category:

  Servlet 3.0+ applications with no .

  Applications with a .

  Applications with a context hierarchy.

  Applications without a context hierarchy.

  All of these should be amenable to translation, but each might require slightly different techniques.

  Servlet 3.0+ applications might translate pretty easily if they already use the Spring Servlet 3.0+ initializer support classes.
Normally, all the code from an existing can be moved into a .
If your existing application has more than one (for example, if it uses ) then you might be able to combine all your context sources into a single .
The main complication you might encounter is if combining does not work and you need to maintain the context hierarchy.
See the entry on building a hierarchy for examples.
An existing parent context that contains web-specific features usually needs to be broken up so that all the components are in the child context.

  Applications that are not already Spring applications might be convertible to Spring Boot applications, and the previously mentioned guidance may help.
However, you may yet encounter problems.
In that case, we suggest asking questions on Stack Overflow with a tag of .

  17.3. Deploying a WAR to WebLogic

  To deploy a Spring Boot application to WebLogic, you must ensure that your servlet initializer directly implements (even if you extend from a base class that already implements it).

  A typical initializer for WebLogic should resemble the following example:

  If you use Logback, you also need to tell WebLogic to prefer the packaged version rather than the version that was pre-installed with the server.
You can do so by adding a file with the following contents:

  17.4. Use Jedis Instead of Lettuce

  By default, the Spring Boot starter () uses Lettuce.
You need to exclude that dependency and include the Jedis one instead.
Spring Boot manages these dependencies to help make this process as easy as possible.

  The following example shows how to do so in Maven:

  The following example shows how to do so in Gradle:

2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/91259.html

(0)
上一篇 2024年 6月 1日 上午9:36
下一篇 2024年 6月 1日

相关推荐

关注微信