(window.webpackJsonp=window.webpackJsonp||[]).push([[53],{484:function(e,t,a){"use strict";a.r(t);var o=a(56),r=Object(o.a)({},(function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[a("h1",{attrs:{id:"how-to-guides"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-to-guides"}},[e._v("#")]),e._v(" “How-to” Guides")]),e._v(" "),a("p",[e._v("This section provides answers to some common ‘how do I do that…​’ questions that often arise when using Spring Boot.\nIts coverage is not exhaustive, but it does cover quite a lot.")]),e._v(" "),a("p",[e._v("If you have a specific problem that we do not cover here, you might want to check "),a("a",{attrs:{href:"https://stackoverflow.com/tags/spring-boot",target:"_blank",rel:"noopener noreferrer"}},[e._v("stackoverflow.com"),a("OutboundLink")],1),e._v(" to see if someone has already provided an answer.\nThis is also a great place to ask new questions (please use the "),a("code",[e._v("spring-boot")]),e._v(" tag).")]),e._v(" "),a("p",[e._v("We are also more than happy to extend this section.\nIf you want to add a ‘how-to’, send us a "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4",target:"_blank",rel:"noopener noreferrer"}},[e._v("pull request"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h2",{attrs:{id:"_1-spring-boot-application"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_1-spring-boot-application"}},[e._v("#")]),e._v(" 1. Spring Boot Application")]),e._v(" "),a("p",[e._v("This section includes topics relating directly to Spring Boot applications.")]),e._v(" "),a("h3",{attrs:{id:"_1-1-create-your-own-failureanalyzer"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_1-1-create-your-own-failureanalyzer"}},[e._v("#")]),e._v(" 1.1. Create Your Own FailureAnalyzer")]),e._v(" "),a("p",[a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/diagnostics/FailureAnalyzer.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("FailureAnalyzer")]),a("OutboundLink")],1),e._v(" is a great way to intercept an exception on startup and turn it into a human-readable message, wrapped in a "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/diagnostics/FailureAnalysis.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("FailureAnalysis")]),a("OutboundLink")],1),e._v(".\nSpring Boot provides such an analyzer for application-context-related exceptions, JSR-303 validations, and more.\nYou can also create your own.")]),e._v(" "),a("p",[a("code",[e._v("AbstractFailureAnalyzer")]),e._v(" is a convenient extension of "),a("code",[e._v("FailureAnalyzer")]),e._v(" that checks the presence of a specified exception type in the exception to handle.\nYou can extend from that so that your implementation gets a chance to handle the exception only when it is actually present.\nIf, for whatever reason, you cannot handle the exception, return "),a("code",[e._v("null")]),e._v(" to give another implementation a chance to handle the exception.")]),e._v(" "),a("p",[a("code",[e._v("FailureAnalyzer")]),e._v(" implementations must be registered in "),a("code",[e._v("META-INF/spring.factories")]),e._v(".\nThe following example registers "),a("code",[e._v("ProjectConstraintViolationFailureAnalyzer")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("org.springframework.boot.diagnostics.FailureAnalyzer=\\\ncom.example.ProjectConstraintViolationFailureAnalyzer\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If you need access to the "),a("code",[e._v("BeanFactory")]),e._v(" or the "),a("code",[e._v("Environment")]),e._v(", your "),a("code",[e._v("FailureAnalyzer")]),e._v(" can implement "),a("code",[e._v("BeanFactoryAware")]),e._v(" or "),a("code",[e._v("EnvironmentAware")]),e._v(" respectively.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_1-2-troubleshoot-auto-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_1-2-troubleshoot-auto-configuration"}},[e._v("#")]),e._v(" 1.2. Troubleshoot Auto-configuration")]),e._v(" "),a("p",[e._v("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.")]),e._v(" "),a("p",[e._v("There is a really useful "),a("code",[e._v("ConditionEvaluationReport")]),e._v(" available in any Spring Boot "),a("code",[e._v("ApplicationContext")]),e._v(".\nYou can see it if you enable "),a("code",[e._v("DEBUG")]),e._v(" logging output.\nIf you use the "),a("code",[e._v("spring-boot-actuator")]),e._v(" (see "),a("RouterLink",{attrs:{to:"/en/spring-boot/actuator.html#actuator"}},[e._v("the Actuator chapter")]),e._v("), there is also a "),a("code",[e._v("conditions")]),e._v(" endpoint that renders the report in JSON.\nUse that endpoint to debug the application and see what features have been added (and which have not been added) by Spring Boot at runtime.")],1),e._v(" "),a("p",[e._v("Many more questions can be answered by looking at the source code and the Javadoc.\nWhen reading the code, remember the following rules of thumb:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("Look for classes called "),a("code",[e._v("*AutoConfiguration")]),e._v(" and read their sources.\nPay special attention to the "),a("code",[e._v("@Conditional*")]),e._v(" annotations to find out what features they enable and when.\nAdd "),a("code",[e._v("--debug")]),e._v(" to the command line or a System property "),a("code",[e._v("-Ddebug")]),e._v(" to get a log on the console of all the auto-configuration decisions that were made in your app.\nIn a running application with actuator enabled, look at the "),a("code",[e._v("conditions")]),e._v(" endpoint ("),a("code",[e._v("/actuator/conditions")]),e._v(" or the JMX equivalent) for the same information.")])]),e._v(" "),a("li",[a("p",[e._v("Look for classes that are "),a("code",[e._v("@ConfigurationProperties")]),e._v(" (such as "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("ServerProperties")]),a("OutboundLink")],1),e._v(") and read from there the available external configuration options.\nThe "),a("code",[e._v("@ConfigurationProperties")]),e._v(" annotation has a "),a("code",[e._v("name")]),e._v(" attribute that acts as a prefix to external properties.\nThus, "),a("code",[e._v("ServerProperties")]),e._v(" has "),a("code",[e._v('prefix="server"')]),e._v(" and its configuration properties are "),a("code",[e._v("server.port")]),e._v(", "),a("code",[e._v("server.address")]),e._v(", and others.\nIn a running application with actuator enabled, look at the "),a("code",[e._v("configprops")]),e._v(" endpoint.")])]),e._v(" "),a("li",[a("p",[e._v("Look for uses of the "),a("code",[e._v("bind")]),e._v(" method on the "),a("code",[e._v("Binder")]),e._v(" to pull configuration values explicitly out of the "),a("code",[e._v("Environment")]),e._v(" in a relaxed manner.\nIt is often used with a prefix.")])]),e._v(" "),a("li",[a("p",[e._v("Look for "),a("code",[e._v("@Value")]),e._v(" annotations that bind directly to the "),a("code",[e._v("Environment")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("Look for "),a("code",[e._v("@ConditionalOnExpression")]),e._v(" annotations that switch features on and off in response to SpEL expressions, normally evaluated with placeholders resolved from the "),a("code",[e._v("Environment")]),e._v(".")])])]),e._v(" "),a("h3",{attrs:{id:"_1-3-customize-the-environment-or-applicationcontext-before-it-starts"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_1-3-customize-the-environment-or-applicationcontext-before-it-starts"}},[e._v("#")]),e._v(" 1.3. Customize the Environment or ApplicationContext Before It Starts")]),e._v(" "),a("p",[e._v("A "),a("code",[e._v("SpringApplication")]),e._v(" has "),a("code",[e._v("ApplicationListeners")]),e._v(" and "),a("code",[e._v("ApplicationContextInitializers")]),e._v(" that are used to apply customizations to the context or environment.\nSpring Boot loads a number of such customizations for use internally from "),a("code",[e._v("META-INF/spring.factories")]),e._v(".\nThere is more than one way to register additional customizations:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("Programmatically, per application, by calling the "),a("code",[e._v("addListeners")]),e._v(" and "),a("code",[e._v("addInitializers")]),e._v(" methods on "),a("code",[e._v("SpringApplication")]),e._v(" before you run it.")])]),e._v(" "),a("li",[a("p",[e._v("Declaratively, per application, by setting the "),a("code",[e._v("context.initializer.classes")]),e._v(" or "),a("code",[e._v("context.listener.classes")]),e._v(" properties.")])]),e._v(" "),a("li",[a("p",[e._v("Declaratively, for all applications, by adding a "),a("code",[e._v("META-INF/spring.factories")]),e._v(" and packaging a jar file that the applications all use as a library.")])])]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("SpringApplication")]),e._v(" sends some special "),a("code",[e._v("ApplicationEvents")]),e._v(" to the listeners (some even before the context is created) and then registers the listeners for events published by the "),a("code",[e._v("ApplicationContext")]),e._v(" as well.\nSee “"),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.spring-application.application-events-and-listeners"}},[e._v("Application Events and Listeners")]),e._v("” in the ‘Spring Boot features’ section for a complete list.")],1),e._v(" "),a("p",[e._v("It is also possible to customize the "),a("code",[e._v("Environment")]),e._v(" before the application context is refreshed by using "),a("code",[e._v("EnvironmentPostProcessor")]),e._v(".\nEach implementation should be registered in "),a("code",[e._v("META-INF/spring.factories")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("org.springframework.boot.env.EnvironmentPostProcessor=com.example.YourEnvironmentPostProcessor\n")])])]),a("p",[e._v("The implementation can load arbitrary files and add them to the "),a("code",[e._v("Environment")]),e._v(".\nFor instance, the following example loads a YAML configuration file from the classpath:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import java.io.IOException;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.env.EnvironmentPostProcessor;\nimport org.springframework.boot.env.YamlPropertySourceLoader;\nimport org.springframework.core.env.ConfigurableEnvironment;\nimport org.springframework.core.env.PropertySource;\nimport org.springframework.core.io.ClassPathResource;\nimport org.springframework.core.io.Resource;\nimport org.springframework.util.Assert;\n\npublic class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {\n\n private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();\n\n @Override\n public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {\n Resource path = new ClassPathResource("com/example/myapp/config.yml");\n PropertySource propertySource = loadYaml(path);\n environment.getPropertySources().addLast(propertySource);\n }\n\n private PropertySource loadYaml(Resource path) {\n Assert.isTrue(path.exists(), () -> "Resource " + path + " does not exist");\n try {\n return this.loader.load("custom-resource", path).get(0);\n }\n catch (IOException ex) {\n throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);\n }\n }\n\n}\n\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The "),a("code",[e._v("Environment")]),e._v(" has already been prepared with all the usual property sources that Spring Boot loads by default."),a("br"),e._v("It is therefore possible to get the location of the file from the environment."),a("br"),e._v("The preceding example adds the "),a("code",[e._v("custom-resource")]),e._v(" property source at the end of the list so that a key defined in any of the usual other locations takes precedence."),a("br"),e._v("A custom implementation may define another order.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("While using "),a("code",[e._v("@PropertySource")]),e._v(" on your "),a("code",[e._v("@SpringBootApplication")]),e._v(" may seem to be a convenient way to load a custom resource in the "),a("code",[e._v("Environment")]),e._v(", we do not recommend it."),a("br"),e._v("Such property sources are not added to the "),a("code",[e._v("Environment")]),e._v(" until the application context is being refreshed."),a("br"),e._v("This is too late to configure certain properties such as "),a("code",[e._v("logging.*")]),e._v(" and "),a("code",[e._v("spring.main.*")]),e._v(" which are read before refresh begins.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_1-4-build-an-applicationcontext-hierarchy-adding-a-parent-or-root-context"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_1-4-build-an-applicationcontext-hierarchy-adding-a-parent-or-root-context"}},[e._v("#")]),e._v(" 1.4. Build an ApplicationContext Hierarchy (Adding a Parent or Root Context)")]),e._v(" "),a("p",[e._v("You can use the "),a("code",[e._v("ApplicationBuilder")]),e._v(" class to create parent/child "),a("code",[e._v("ApplicationContext")]),e._v(" hierarchies.\nSee “"),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.spring-application.fluent-builder-api"}},[e._v("features.html")]),e._v("” in the ‘Spring Boot features’ section for more information.")],1),e._v(" "),a("h3",{attrs:{id:"_1-5-create-a-non-web-application"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_1-5-create-a-non-web-application"}},[e._v("#")]),e._v(" 1.5. Create a Non-web Application")]),e._v(" "),a("p",[e._v("Not all Spring applications have to be web applications (or web services).\nIf you want to execute some code in a "),a("code",[e._v("main")]),e._v(" method but also bootstrap a Spring application to set up the infrastructure to use, you can use the "),a("code",[e._v("SpringApplication")]),e._v(" features of Spring Boot.\nA "),a("code",[e._v("SpringApplication")]),e._v(" changes its "),a("code",[e._v("ApplicationContext")]),e._v(" class, depending on whether it thinks it needs a web application or not.\nThe first thing you can do to help it is to leave server-related dependencies (such as the servlet API) off the classpath.\nIf you cannot do that (for example, you run two applications from the same code base) then you can explicitly call "),a("code",[e._v("setWebApplicationType(WebApplicationType.NONE)")]),e._v(" on your "),a("code",[e._v("SpringApplication")]),e._v(" instance or set the "),a("code",[e._v("applicationContextClass")]),e._v(" property (through the Java API or with external properties).\nApplication code that you want to run as your business logic can be implemented as a "),a("code",[e._v("CommandLineRunner")]),e._v(" and dropped into the context as a "),a("code",[e._v("@Bean")]),e._v(" definition.")]),e._v(" "),a("h2",{attrs:{id:"_2-properties-and-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-properties-and-configuration"}},[e._v("#")]),e._v(" 2. Properties and Configuration")]),e._v(" "),a("p",[e._v("This section includes topics about setting and reading properties and configuration settings and their interaction with Spring Boot applications.")]),e._v(" "),a("h3",{attrs:{id:"_2-1-automatically-expand-properties-at-build-time"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-automatically-expand-properties-at-build-time"}},[e._v("#")]),e._v(" 2.1. Automatically Expand Properties at Build Time")]),e._v(" "),a("p",[e._v("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.\nThis is possible in both Maven and Gradle.")]),e._v(" "),a("h4",{attrs:{id:"_2-1-1-automatic-property-expansion-using-maven"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-1-automatic-property-expansion-using-maven"}},[e._v("#")]),e._v(" 2.1.1. Automatic Property Expansion Using Maven")]),e._v(" "),a("p",[e._v("You can automatically expand properties from the Maven project by using resource filtering.\nIf you use the "),a("code",[e._v("spring-boot-starter-parent")]),e._v(", you can then refer to your Maven ‘project properties’ with "),a("code",[e._v("@[[email protected]](/cdn-cgi/l/email-protection)")]),e._v(" placeholders, as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("[email protected]@\n[email protected]@\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('app:\n encoding: "@[email protected]"\n java:\n version: "@[email protected]"\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Only production configuration is filtered that way (in other words, no filtering is applied on "),a("code",[e._v("src/test/resources")]),e._v(").")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If you enable the "),a("code",[e._v("addResources")]),e._v(" flag, the "),a("code",[e._v("spring-boot:run")]),e._v(" goal can add "),a("code",[e._v("src/main/resources")]),e._v(" directly to the classpath (for hot reloading purposes)."),a("br"),e._v("Doing so circumvents the resource filtering and this feature."),a("br"),e._v("Instead, you can use the "),a("code",[e._v("exec:java")]),e._v(" goal or customize the plugin’s configuration."),a("br"),e._v("See the "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#getting-started",target:"_blank",rel:"noopener noreferrer"}},[e._v("plugin usage page"),a("OutboundLink")],1),e._v(" for more details.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("If you do not use the starter parent, you need to include the following element inside the "),a("code",[e._v("")]),e._v(" element of your "),a("code",[e._v("pom.xml")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n src/main/resources\n true\n \n\n")])])]),a("p",[e._v("You also need to include the following element inside "),a("code",[e._v("")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n org.apache.maven.plugins\n maven-resources-plugin\n 2.7\n \n \n @\n \n false\n \n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The "),a("code",[e._v("useDefaultDelimiters")]),e._v(" property is important if you use standard Spring placeholders (such as "),a("code",[e._v("${placeholder}")]),e._v(") in your configuration."),a("br"),e._v("If that property is not set to "),a("code",[e._v("false")]),e._v(", these may be expanded by the build.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_2-1-2-automatic-property-expansion-using-gradle"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-1-2-automatic-property-expansion-using-gradle"}},[e._v("#")]),e._v(" 2.1.2. Automatic Property Expansion Using Gradle")]),e._v(" "),a("p",[e._v("You can automatically expand properties from the Gradle project by configuring the Java plugin’s "),a("code",[e._v("processResources")]),e._v(" task to do so, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("processResources {\n expand(project.properties)\n}\n")])])]),a("p",[e._v("You can then refer to your Gradle project’s properties by using placeholders, as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("app.name=${name}\napp.description=${description}\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('app:\n name: "${name}"\n description: "${description}"\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Gradle’s "),a("code",[e._v("expand")]),e._v(" method uses Groovy’s "),a("code",[e._v("SimpleTemplateEngine")]),e._v(", which transforms "),a("code",[e._v("${..}")]),e._v(" tokens."),a("br"),e._v("The "),a("code",[e._v("${..}")]),e._v(" style conflicts with Spring’s own property placeholder mechanism."),a("br"),e._v("To use Spring property placeholders together with automatic expansion, escape the Spring property placeholders as follows: "),a("code",[e._v("\\${..}")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_2-2-externalize-the-configuration-of-springapplication"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-2-externalize-the-configuration-of-springapplication"}},[e._v("#")]),e._v(" 2.2. Externalize the Configuration of SpringApplication")]),e._v(" "),a("p",[e._v("A "),a("code",[e._v("SpringApplication")]),e._v(" has bean property setters, so you can use its Java API as you create the application to modify its behavior.\nAlternatively, you can externalize the configuration by setting properties in "),a("code",[e._v("spring.main.*")]),e._v(".\nFor example, in "),a("code",[e._v("application.properties")]),e._v(", you might have the following settings:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.main.web-application-type=none\nspring.main.banner-mode=off\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n main:\n web-application-type: "none"\n banner-mode: "off"\n')])])]),a("p",[e._v("Then the Spring Boot banner is not printed on startup, and the application is not starting an embedded web server.")]),e._v(" "),a("p",[e._v("Properties defined in external configuration override and replace the values specified with the Java API, with the notable exception of the primary sources.\nPrimary sources are those provided to the "),a("code",[e._v("SpringApplication")]),e._v(" constructor:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.Banner;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class MyApplication {\n\n public static void main(String[] args) {\n SpringApplication application = new SpringApplication(MyApplication.class);\n application.setBannerMode(Banner.Mode.OFF);\n application.run(args);\n }\n\n}\n\n")])])]),a("p",[e._v("Or to "),a("code",[e._v("sources(…​)")]),e._v(" method of a "),a("code",[e._v("SpringApplicationBuilder")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.Banner;\nimport org.springframework.boot.builder.SpringApplicationBuilder;\n\npublic class MyApplication {\n\n public static void main(String[] args) {\n new SpringApplicationBuilder()\n .bannerMode(Banner.Mode.OFF)\n .sources(MyApplication.class)\n .run(args);\n }\n\n}\n\n")])])]),a("p",[e._v("Given the examples above, if we have the following configuration:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.main.sources=com.example.MyDatabaseConfig,com.example.MyJmsConfig\nspring.main.banner-mode=console\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n main:\n sources: "com.example.MyDatabaseConfig,com.example.MyJmsConfig"\n banner-mode: "console"\n')])])]),a("p",[e._v("The actual application will show the banner (as overridden by configuration) and uses three sources for the "),a("code",[e._v("ApplicationContext")]),e._v(".\nThe application sources are:")]),e._v(" "),a("ol",[a("li",[a("p",[a("code",[e._v("MyApplication")]),e._v(" (from the code)")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("MyDatabaseConfig")]),e._v(" (from the external config)")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("MyJmsConfig")]),e._v("(from the external config)")])])]),e._v(" "),a("h3",{attrs:{id:"_2-3-change-the-location-of-external-properties-of-an-application"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-3-change-the-location-of-external-properties-of-an-application"}},[e._v("#")]),e._v(" 2.3. Change the Location of External Properties of an Application")]),e._v(" "),a("p",[e._v("By default, properties from different sources are added to the Spring "),a("code",[e._v("Environment")]),e._v(" in a defined order (see “"),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.external-config"}},[e._v("features.html")]),e._v("” in the ‘Spring Boot features’ section for the exact order).")],1),e._v(" "),a("p",[e._v("You can also provide the following System properties (or environment variables) to change the behavior:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("spring.config.name")]),e._v(" ("),a("code",[e._v("SPRING_CONFIG_NAME")]),e._v("): Defaults to "),a("code",[e._v("application")]),e._v(" as the root of the file name.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("spring.config.location")]),e._v(" ("),a("code",[e._v("SPRING_CONFIG_LOCATION")]),e._v("): The file to load (such as a classpath resource or a URL).\nA separate "),a("code",[e._v("Environment")]),e._v(" property source is set up for this document and it can be overridden by system properties, environment variables, or the command line.")])])]),e._v(" "),a("p",[e._v("No matter what you set in the environment, Spring Boot always loads "),a("code",[e._v("application.properties")]),e._v(" as described above.\nBy default, if YAML is used, then files with the ‘.yml’ extension are also added to the list.")]),e._v(" "),a("p",[e._v("Spring Boot logs the configuration files that are loaded at the "),a("code",[e._v("DEBUG")]),e._v(" level and the candidates it has not found at "),a("code",[e._v("TRACE")]),e._v(" level.")]),e._v(" "),a("p",[e._v("See "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigFileApplicationListener.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("ConfigFileApplicationListener")]),a("OutboundLink")],1),e._v(" for more detail.")]),e._v(" "),a("h3",{attrs:{id:"_2-4-use-short-command-line-arguments"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-4-use-short-command-line-arguments"}},[e._v("#")]),e._v(" 2.4. Use ‘Short’ Command Line Arguments")]),e._v(" "),a("p",[e._v("Some people like to use (for example) "),a("code",[e._v("--port=9000")]),e._v(" instead of "),a("code",[e._v("--server.port=9000")]),e._v(" to set configuration properties on the command line.\nYou can enable this behavior by using placeholders in "),a("code",[e._v("application.properties")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.port=${port:8080}\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n port: "${port:8080}"\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If you inherit from the "),a("code",[e._v("spring-boot-starter-parent")]),e._v(" POM, the default filter token of the "),a("code",[e._v("maven-resources-plugins")]),e._v(" has been changed from "),a("code",[e._v("${*}")]),e._v(" to "),a("code",[e._v("@")]),e._v(" (that is, "),a("code",[e._v("@[[email protected]](/cdn-cgi/l/email-protection)")]),e._v(" instead of "),a("code",[e._v("${maven.token}")]),e._v(") to prevent conflicts with Spring-style placeholders."),a("br"),e._v("If you have enabled Maven filtering for the "),a("code",[e._v("application.properties")]),e._v(" directly, you may want to also change the default filter token to use "),a("a",{attrs:{href:"https://maven.apache.org/plugins/maven-resources-plugin/resources-mojo.html#delimiters",target:"_blank",rel:"noopener noreferrer"}},[e._v("other delimiters"),a("OutboundLink")],1),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("In this specific case, the port binding works in a PaaS environment such as Heroku or Cloud Foundry."),a("br"),e._v("In those two platforms, the "),a("code",[e._v("PORT")]),e._v(" environment variable is set automatically and Spring can bind to capitalized synonyms for "),a("code",[e._v("Environment")]),e._v(" properties.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_2-5-use-yaml-for-external-properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-5-use-yaml-for-external-properties"}},[e._v("#")]),e._v(" 2.5. Use YAML for External Properties")]),e._v(" "),a("p",[e._v("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:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n application:\n name: "cruncher"\n datasource:\n driver-class-name: "com.mysql.jdbc.Driver"\n url: "jdbc:mysql://localhost/test"\nserver:\n port: 9000\n')])])]),a("p",[e._v("Create a file called "),a("code",[e._v("application.yml")]),e._v(" and put it in the root of your classpath.\nThen add "),a("code",[e._v("snakeyaml")]),e._v(" to your dependencies (Maven coordinates "),a("code",[e._v("org.yaml:snakeyaml")]),e._v(", already included if you use the "),a("code",[e._v("spring-boot-starter")]),e._v(").\nA YAML file is parsed to a Java "),a("code",[e._v("Map")]),e._v(" (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 "),a("code",[e._v("Properties")]),e._v(" files in Java.")]),e._v(" "),a("p",[e._v("The preceding example YAML corresponds to the following "),a("code",[e._v("application.properties")]),e._v(" file:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.application.name=cruncher\nspring.datasource.driver-class-name=com.mysql.jdbc.Driver\nspring.datasource.url=jdbc:mysql://localhost/test\nserver.port=9000\n")])])]),a("p",[e._v("See “"),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.external-config.yaml"}},[e._v("features.html")]),e._v("” in the ‘Spring Boot features’ section for more information about YAML.")],1),e._v(" "),a("h3",{attrs:{id:"_2-6-set-the-active-spring-profiles"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-6-set-the-active-spring-profiles"}},[e._v("#")]),e._v(" 2.6. Set the Active Spring Profiles")]),e._v(" "),a("p",[e._v("The Spring "),a("code",[e._v("Environment")]),e._v(" has an API for this, but you would normally set a System property ("),a("code",[e._v("spring.profiles.active")]),e._v(") or an OS environment variable ("),a("code",[e._v("SPRING_PROFILES_ACTIVE")]),e._v(").\nAlso, you can launch your application with a "),a("code",[e._v("-D")]),e._v(" argument (remember to put it before the main class or jar archive), as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar\n")])])]),a("p",[e._v("In Spring Boot, you can also set the active profile in "),a("code",[e._v("application.properties")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.profiles.active=production\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n profiles:\n active: "production"\n')])])]),a("p",[e._v("A value set this way is replaced by the System property or environment variable setting but not by the "),a("code",[e._v("SpringApplicationBuilder.profiles()")]),e._v(" method.\nThus, the latter Java API can be used to augment the profiles without changing the defaults.")]),e._v(" "),a("p",[e._v("See “"),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.profiles"}},[e._v("features.html")]),e._v("” in the “Spring Boot features” section for more information.")],1),e._v(" "),a("h3",{attrs:{id:"_2-7-set-the-default-profile-name"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-7-set-the-default-profile-name"}},[e._v("#")]),e._v(" 2.7. Set the Default Profile Name")]),e._v(" "),a("p",[e._v("The default profile is a profile that is enabled if no profile is active.\nBy default, the name of the default profile is "),a("code",[e._v("default")]),e._v(", but it could be changed using a System property ("),a("code",[e._v("spring.profiles.default")]),e._v(") or an OS environment variable ("),a("code",[e._v("SPRING_PROFILES_DEFAULT")]),e._v(").")]),e._v(" "),a("p",[e._v("In Spring Boot, you can also set the default profile name in "),a("code",[e._v("application.properties")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.profiles.default=dev\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n profiles:\n default: "dev"\n')])])]),a("p",[e._v("See “"),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.profiles"}},[e._v("features.html")]),e._v("” in the “Spring Boot features” section for more information.")],1),e._v(" "),a("h3",{attrs:{id:"_2-8-change-configuration-depending-on-the-environment"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-8-change-configuration-depending-on-the-environment"}},[e._v("#")]),e._v(" 2.8. Change Configuration Depending on the Environment")]),e._v(" "),a("p",[e._v("Spring Boot supports multi-document YAML and Properties files (see "),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.external-config.files.multi-document"}},[e._v("features.html")]),e._v(" for details) which can be activated conditionally based on the active profiles.")],1),e._v(" "),a("p",[e._v("If a document contains a "),a("code",[e._v("spring.config.activate.on-profile")]),e._v(" key, then the profiles value (a comma-separated list of profiles or a profile expression) is fed into the Spring "),a("code",[e._v("Environment.acceptsProfiles()")]),e._v(" method.\nIf the profile expression matches then that document is included in the final merge (otherwise, it is not), as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.port=9000\n#---\nspring.config.activate.on-profile=development\nserver.port=9001\n#---\nspring.config.activate.on-profile=production\nserver.port=0\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n port: 9000\n---\nspring:\n config:\n activate:\n on-profile: "development"\nserver:\n port: 9001\n---\nspring:\n config:\n activate:\n on-profile: "production"\nserver:\n port: 0\n')])])]),a("p",[e._v("In the preceding example, the default port is 9000.\nHowever, if the Spring profile called ‘development’ is active, then the port is 9001.\nIf ‘production’ is active, then the port is 0.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The documents are merged in the order in which they are encountered."),a("br"),e._v("Later values override earlier values.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_2-9-discover-built-in-options-for-external-properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_2-9-discover-built-in-options-for-external-properties"}},[e._v("#")]),e._v(" 2.9. Discover Built-in Options for External Properties")]),e._v(" "),a("p",[e._v("Spring Boot binds external properties from "),a("code",[e._v("application.properties")]),e._v(" (or "),a("code",[e._v(".yml")]),e._v(" files and other places) into an application at runtime.\nThere 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.")]),e._v(" "),a("p",[e._v("A running application with the Actuator features has a "),a("code",[e._v("configprops")]),e._v(" endpoint that shows all the bound and bindable properties available through "),a("code",[e._v("@ConfigurationProperties")]),e._v(".")]),e._v(" "),a("p",[e._v("The appendix includes an "),a("RouterLink",{attrs:{to:"/en/spring-boot/application-properties.html#appendix.application-properties"}},[a("code",[e._v("application.properties")])]),e._v(" example with a list of the most common properties supported by Spring Boot.\nThe definitive list comes from searching the source code for "),a("code",[e._v("@ConfigurationProperties")]),e._v(" and "),a("code",[e._v("@Value")]),e._v(" annotations as well as the occasional use of "),a("code",[e._v("Binder")]),e._v('.\nFor more about the exact ordering of loading properties, see "'),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.external-config"}},[e._v("features.html")]),e._v('".')],1),e._v(" "),a("h2",{attrs:{id:"_3-embedded-web-servers"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-embedded-web-servers"}},[e._v("#")]),e._v(" 3. Embedded Web Servers")]),e._v(" "),a("p",[e._v("Each Spring Boot web application includes an embedded web server.\nThis feature leads to a number of how-to questions, including how to change the embedded server and how to configure the embedded server.\nThis section answers those questions.")]),e._v(" "),a("h3",{attrs:{id:"_3-1-use-another-web-server"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-1-use-another-web-server"}},[e._v("#")]),e._v(" 3.1. Use Another Web Server")]),e._v(" "),a("p",[e._v("Many Spring Boot starters include default embedded containers.")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("For servlet stack applications, the "),a("code",[e._v("spring-boot-starter-web")]),e._v(" includes Tomcat by including "),a("code",[e._v("spring-boot-starter-tomcat")]),e._v(", but you can use "),a("code",[e._v("spring-boot-starter-jetty")]),e._v(" or "),a("code",[e._v("spring-boot-starter-undertow")]),e._v(" instead.")])]),e._v(" "),a("li",[a("p",[e._v("For reactive stack applications, the "),a("code",[e._v("spring-boot-starter-webflux")]),e._v(" includes Reactor Netty by including "),a("code",[e._v("spring-boot-starter-reactor-netty")]),e._v(", but you can use "),a("code",[e._v("spring-boot-starter-tomcat")]),e._v(", "),a("code",[e._v("spring-boot-starter-jetty")]),e._v(", or "),a("code",[e._v("spring-boot-starter-undertow")]),e._v(" instead.")])])]),e._v(" "),a("p",[e._v("When switching to a different HTTP server, you need to swap the default dependencies for those that you need instead.\nTo help with this process, Spring Boot provides a separate starter for each of the supported HTTP servers.")]),e._v(" "),a("p",[e._v("The following Maven example shows how to exclude Tomcat and include Jetty for Spring MVC:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n 3.1.0\n\n\n org.springframework.boot\n spring-boot-starter-web\n \n \x3c!-- Exclude the Tomcat dependency --\x3e\n \n org.springframework.boot\n spring-boot-starter-tomcat\n \n \n\n\x3c!-- Use Jetty instead --\x3e\n\n org.springframework.boot\n spring-boot-starter-jetty\n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The version of the servlet API has been overridden as, unlike Tomcat 9 and Undertow 2, Jetty 9.4 does not support servlet 4.0."),a("br"),e._v("If you wish to use Jetty 10, which does support servlet 4.0, override the "),a("code",[e._v("jetty.version")]),e._v(" property rather than the "),a("code",[e._v("servlet-api.version")]),e._v(" property.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The following Gradle example configures the necessary dependencies and a "),a("a",{attrs:{href:"https://docs.gradle.org/current/userguide/resolution_rules.html#sec:module_replacement",target:"_blank",rel:"noopener noreferrer"}},[e._v("module replacement"),a("OutboundLink")],1),e._v(" to use Undertow in place of Reactor Netty for Spring WebFlux:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('dependencies {\n implementation "org.springframework.boot:spring-boot-starter-undertow"\n implementation "org.springframework.boot:spring-boot-starter-webflux"\n modules {\n module("org.springframework.boot:spring-boot-starter-reactor-netty") {\n replacedBy("org.springframework.boot:spring-boot-starter-undertow", "Use Undertow instead of Reactor Netty")\n }\n }\n}\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[a("code",[e._v("spring-boot-starter-reactor-netty")]),e._v(" is required to use the "),a("code",[e._v("WebClient")]),e._v(" class, so you may need to keep a dependency on Netty even when you need to include a different HTTP server.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_3-2-disabling-the-web-server"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-2-disabling-the-web-server"}},[e._v("#")]),e._v(" 3.2. Disabling the Web Server")]),e._v(" "),a("p",[e._v("If your classpath contains the necessary bits to start a web server, Spring Boot will automatically start it.\nTo disable this behavior configure the "),a("code",[e._v("WebApplicationType")]),e._v(" in your "),a("code",[e._v("application.properties")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.main.web-application-type=none\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n main:\n web-application-type: "none"\n')])])]),a("h3",{attrs:{id:"_3-3-change-the-http-port"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-3-change-the-http-port"}},[e._v("#")]),e._v(" 3.3. Change the HTTP Port")]),e._v(" "),a("p",[e._v("In a standalone application, the main HTTP port defaults to "),a("code",[e._v("8080")]),e._v(" but can be set with "),a("code",[e._v("server.port")]),e._v(" (for example, in "),a("code",[e._v("application.properties")]),e._v(" or as a System property).\nThanks to relaxed binding of "),a("code",[e._v("Environment")]),e._v(" values, you can also use "),a("code",[e._v("SERVER_PORT")]),e._v(" (for example, as an OS environment variable).")]),e._v(" "),a("p",[e._v("To switch off the HTTP endpoints completely but still create a "),a("code",[e._v("WebApplicationContext")]),e._v(", use "),a("code",[e._v("server.port=-1")]),e._v(" (doing so is sometimes useful for testing).")]),e._v(" "),a("p",[e._v("For more details, see “"),a("RouterLink",{attrs:{to:"/en/spring-boot/web.html#web.servlet.embedded-container.customizing"}},[e._v("web.html")]),e._v("” in the ‘Spring Boot Features’ section, or the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("ServerProperties")]),a("OutboundLink")],1),e._v(" source code.")],1),e._v(" "),a("h3",{attrs:{id:"_3-4-use-a-random-unassigned-http-port"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-4-use-a-random-unassigned-http-port"}},[e._v("#")]),e._v(" 3.4. Use a Random Unassigned HTTP Port")]),e._v(" "),a("p",[e._v("To scan for a free port (using OS natives to prevent clashes) use "),a("code",[e._v("server.port=0")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_3-5-discover-the-http-port-at-runtime"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-5-discover-the-http-port-at-runtime"}},[e._v("#")]),e._v(" 3.5. Discover the HTTP Port at Runtime")]),e._v(" "),a("p",[e._v("You can access the port the server is running on from log output or from the "),a("code",[e._v("WebServerApplicationContext")]),e._v(" through its "),a("code",[e._v("WebServer")]),e._v(".\nThe best way to get that and be sure it has been initialized is to add a "),a("code",[e._v("@Bean")]),e._v(" of type "),a("code",[e._v("ApplicationListener")]),e._v(" and pull the container out of the event when it is published.")]),e._v(" "),a("p",[e._v("Tests that use "),a("code",[e._v("@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)")]),e._v(" can also inject the actual port into a field by using the "),a("code",[e._v("@LocalServerPort")]),e._v(" annotation, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.boot.test.context.SpringBootTest.WebEnvironment;\nimport org.springframework.boot.web.server.LocalServerPort;\n\n@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)\npublic class MyWebIntegrationTests {\n\n @LocalServerPort\n int port;\n\n // ...\n\n}\n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[a("code",[e._v("@LocalServerPort")]),e._v(" is a meta-annotation for "),a("code",[e._v('@Value("${local.server.port}")')]),e._v("."),a("br"),e._v("Do not try to inject the port in a regular application."),a("br"),e._v("As we just saw, the value is set only after the container has been initialized."),a("br"),e._v("Contrary to a test, application code callbacks are processed early (before the value is actually available).")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_3-6-enable-http-response-compression"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-6-enable-http-response-compression"}},[e._v("#")]),e._v(" 3.6. Enable HTTP Response Compression")]),e._v(" "),a("p",[e._v("HTTP response compression is supported by Jetty, Tomcat, and Undertow.\nIt can be enabled in "),a("code",[e._v("application.properties")]),e._v(", as follows:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.compression.enabled=true\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server:\n compression:\n enabled: true\n")])])]),a("p",[e._v("By default, responses must be at least 2048 bytes in length for compression to be performed.\nYou can configure this behavior by setting the "),a("code",[e._v("server.compression.min-response-size")]),e._v(" property.")]),e._v(" "),a("p",[e._v("By default, responses are compressed only if their content type is one of the following:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("text/html")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("text/xml")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("text/plain")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("text/css")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("text/javascript")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("application/javascript")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("application/json")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("application/xml")])])])]),e._v(" "),a("p",[e._v("You can configure this behavior by setting the "),a("code",[e._v("server.compression.mime-types")]),e._v(" property.")]),e._v(" "),a("h3",{attrs:{id:"_3-7-configure-ssl"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-7-configure-ssl"}},[e._v("#")]),e._v(" 3.7. Configure SSL")]),e._v(" "),a("p",[e._v("SSL can be configured declaratively by setting the various "),a("code",[e._v("server.ssl.*")]),e._v(" properties, typically in "),a("code",[e._v("application.properties")]),e._v(" or "),a("code",[e._v("application.yml")]),e._v(".\nThe following example shows setting SSL properties in "),a("code",[e._v("application.properties")]),e._v(":")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.port=8443\nserver.ssl.key-store=classpath:keystore.jks\nserver.ssl.key-store-password=secret\nserver.ssl.key-password=another-secret\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n port: 8443\n ssl:\n key-store: "classpath:keystore.jks"\n key-store-password: "secret"\n key-password: "another-secret"\n')])])]),a("p",[e._v("See "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/server/Ssl.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("Ssl")]),a("OutboundLink")],1),e._v(" for details of all of the supported properties.")]),e._v(" "),a("p",[e._v("Using configuration such as the preceding example means the application no longer supports a plain HTTP connector at port 8080.\nSpring Boot does not support the configuration of both an HTTP connector and an HTTPS connector through "),a("code",[e._v("application.properties")]),e._v(".\nIf you want to have both, you need to configure one of them programmatically.\nWe recommend using "),a("code",[e._v("application.properties")]),e._v(" to configure HTTPS, as the HTTP connector is the easier of the two to configure programmatically.")]),e._v(" "),a("h3",{attrs:{id:"_3-8-configure-http-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-configure-http-2"}},[e._v("#")]),e._v(" 3.8. Configure HTTP/2")]),e._v(" "),a("p",[e._v("You can enable HTTP/2 support in your Spring Boot application with the "),a("code",[e._v("server.http2.enabled")]),e._v(" configuration property.\nBoth "),a("code",[e._v("h2")]),e._v(" (HTTP/2 over TLS) and "),a("code",[e._v("h2c")]),e._v(" (HTTP/2 over TCP) are supported.\nTo use "),a("code",[e._v("h2")]),e._v(", SSL must also be enabled.\nWhen SSL is not enabled, "),a("code",[e._v("h2c")]),e._v(" will be used.\nThe details of the "),a("code",[e._v("h2")]),e._v(" support depend on the chosen web server and the application environment, since that protocol is not supported out-of-the-box by all JDK 8 releases.")]),e._v(" "),a("h4",{attrs:{id:"_3-8-1-http-2-with-tomcat"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-1-http-2-with-tomcat"}},[e._v("#")]),e._v(" 3.8.1. HTTP/2 with Tomcat")]),e._v(" "),a("p",[e._v("Spring Boot ships by default with Tomcat 9.0.x which supports "),a("code",[e._v("h2c")]),e._v(" out of the box and "),a("code",[e._v("h2")]),e._v(" out of the box when using JDK 9 or later.\nAlternatively, "),a("code",[e._v("h2")]),e._v(" can be used on JDK 8 if the "),a("code",[e._v("libtcnative")]),e._v(" library and its dependencies are installed on the host operating system.")]),e._v(" "),a("p",[e._v("The library directory must be made available, if not already, to the JVM library path.\nYou can do so with a JVM argument such as "),a("code",[e._v("-Djava.library.path=/usr/local/opt/tomcat-native/lib")]),e._v(".\nMore on this in the "),a("a",{attrs:{href:"https://tomcat.apache.org/tomcat-9.0-doc/apr.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("official Tomcat documentation"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("p",[e._v("Starting Tomcat 9.0.x on JDK 8 with HTTP/2 and SSL enabled but without that native support logs the following error:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('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.\n')])])]),a("p",[e._v("This error is not fatal, and the application still starts with HTTP/1.1 SSL support.")]),e._v(" "),a("h4",{attrs:{id:"_3-8-2-http-2-with-jetty"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-2-http-2-with-jetty"}},[e._v("#")]),e._v(" 3.8.2. HTTP/2 with Jetty")]),e._v(" "),a("p",[e._v("For HTTP/2 support, Jetty requires the additional "),a("code",[e._v("org.eclipse.jetty.http2:http2-server")]),e._v(" dependency.\nTo use "),a("code",[e._v("h2c")]),e._v(" no other dependencies are required.\nTo use "),a("code",[e._v("h2")]),e._v(", you also need to choose one of the following dependencies, depending on your deployment:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("org.eclipse.jetty:jetty-alpn-java-server")]),e._v(" for applications running on JDK9+")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("org.eclipse.jetty:jetty-alpn-openjdk8-server")]),e._v(" for applications running on JDK8u252+")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("org.eclipse.jetty:jetty-alpn-conscrypt-server")]),e._v(" and the "),a("a",{attrs:{href:"https://www.conscrypt.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Conscrypt library"),a("OutboundLink")],1),e._v(" with no JDK requirement")])])]),e._v(" "),a("h4",{attrs:{id:"_3-8-3-http-2-with-reactor-netty"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-3-http-2-with-reactor-netty"}},[e._v("#")]),e._v(" 3.8.3. HTTP/2 with Reactor Netty")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("spring-boot-webflux-starter")]),e._v(" is using by default Reactor Netty as a server.\nReactor Netty supports "),a("code",[e._v("h2c")]),e._v(" using JDK 8 or later with no additional dependencies.\nReactor Netty supports "),a("code",[e._v("h2")]),e._v(" using the JDK support with JDK 9 or later.\nFor JDK 8 environments, or for optimal runtime performance, this server also supports "),a("code",[e._v("h2")]),e._v(" with native libraries.\nTo enable that, your application needs to have an additional dependency.")]),e._v(" "),a("p",[e._v("Spring Boot manages the version for the "),a("code",[e._v("io.netty:netty-tcnative-boringssl-static")]),e._v(' "uber jar", containing native libraries for all platforms.\nDevelopers can choose to import only the required dependencies using a classifier (see '),a("a",{attrs:{href:"https://netty.io/wiki/forked-tomcat-native.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("the Netty official documentation"),a("OutboundLink")],1),e._v(").")]),e._v(" "),a("h4",{attrs:{id:"_3-8-4-http-2-with-undertow"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-8-4-http-2-with-undertow"}},[e._v("#")]),e._v(" 3.8.4. HTTP/2 with Undertow")]),e._v(" "),a("p",[e._v("As of Undertow 1.4.0+, both "),a("code",[e._v("h2")]),e._v(" and "),a("code",[e._v("h2c")]),e._v(" are supported on JDK 8 without any additional dependencies.")]),e._v(" "),a("h3",{attrs:{id:"_3-9-configure-the-web-server"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-9-configure-the-web-server"}},[e._v("#")]),e._v(" 3.9. Configure the Web Server")]),e._v(" "),a("p",[e._v("Generally, you should first consider using one of the many available configuration keys and customize your web server by adding new entries in your "),a("code",[e._v("application.properties")]),e._v(" or "),a("code",[e._v("application.yml")]),e._v(" file.\nSee “"),a("a",{attrs:{href:"#howto.properties-and-configuration.discover-build-in-options-for-external-properties"}},[e._v("Discover Built-in Options for External Properties")]),e._v("”).\nThe "),a("code",[e._v("server.*")]),e._v(" namespace is quite useful here, and it includes namespaces like "),a("code",[e._v("server.tomcat.*")]),e._v(", "),a("code",[e._v("server.jetty.*")]),e._v(" and others, for server-specific features.\nSee the list of "),a("RouterLink",{attrs:{to:"/en/spring-boot/application-properties.html#appendix.application-properties"}},[e._v("application-properties.html")]),e._v(".")],1),e._v(" "),a("p",[e._v("The previous sections covered already many common use cases, such as compression, SSL or HTTP/2.\nHowever, if a configuration key does not exist for your use case, you should then look at "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/api/org/springframework/boot/web/server/WebServerFactoryCustomizer.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("WebServerFactoryCustomizer")]),a("OutboundLink")],1),e._v(".\nYou 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).")]),e._v(" "),a("p",[e._v("The example below is for Tomcat with the "),a("code",[e._v("spring-boot-starter-web")]),e._v(" (servlet stack):")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;\nimport org.springframework.boot.web.server.WebServerFactoryCustomizer;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer {\n\n @Override\n public void customize(TomcatServletWebServerFactory factory) {\n // customize the factory here\n }\n\n}\n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Spring Boot uses that infrastructure internally to auto-configure the server."),a("br"),e._v("Auto-configured "),a("code",[e._v("WebServerFactoryCustomizer")]),e._v(" beans have an order of "),a("code",[e._v("0")]),e._v(" and will be processed before any user-defined customizers, unless it has an explicit order that states otherwise.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Once you have got access to a "),a("code",[e._v("WebServerFactory")]),e._v(" using the customizer, you can use it to configure specific parts, like connectors, server resources, or the server itself - all using server-specific APIs.")]),e._v(" "),a("p",[e._v("In addition Spring Boot provides:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Server")]),e._v(" "),a("th",[e._v("Servlet stack")]),e._v(" "),a("th",[e._v("Reactive stack")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[e._v("Tomcat")]),e._v(" "),a("td",[a("code",[e._v("TomcatServletWebServerFactory")])]),e._v(" "),a("td",[a("code",[e._v("TomcatReactiveWebServerFactory")])])]),e._v(" "),a("tr",[a("td",[e._v("Jetty")]),e._v(" "),a("td",[a("code",[e._v("JettyServletWebServerFactory")])]),e._v(" "),a("td",[a("code",[e._v("JettyReactiveWebServerFactory")])])]),e._v(" "),a("tr",[a("td",[e._v("Undertow")]),e._v(" "),a("td",[a("code",[e._v("UndertowServletWebServerFactory")])]),e._v(" "),a("td",[a("code",[e._v("UndertowReactiveWebServerFactory")])])]),e._v(" "),a("tr",[a("td",[e._v("Reactor")]),e._v(" "),a("td",[e._v("N/A")]),e._v(" "),a("td",[a("code",[e._v("NettyReactiveWebServerFactory")])])])])]),e._v(" "),a("p",[e._v("As a last resort, you can also declare your own "),a("code",[e._v("WebServerFactory")]),e._v(" bean, which will override the one provided by Spring Boot.\nWhen you do so, auto-configured customizers are still applied on your custom factory, so use that option carefully.")]),e._v(" "),a("h3",{attrs:{id:"_3-10-add-a-servlet-filter-or-listener-to-an-application"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-10-add-a-servlet-filter-or-listener-to-an-application"}},[e._v("#")]),e._v(" 3.10. Add a Servlet, Filter, or Listener to an Application")]),e._v(" "),a("p",[e._v("In a servlet stack application, that is with the "),a("code",[e._v("spring-boot-starter-web")]),e._v(", there are two ways to add "),a("code",[e._v("Servlet")]),e._v(", "),a("code",[e._v("Filter")]),e._v(", "),a("code",[e._v("ServletContextListener")]),e._v(", and the other listeners supported by the Servlet API to your application:")]),e._v(" "),a("ul",[a("li",[a("p",[a("a",{attrs:{href:"#howto.webserver.add-servlet-filter-listener.spring-bean"}},[e._v("Add a Servlet, Filter, or Listener by Using a Spring Bean")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#howto.webserver.add-servlet-filter-listener.using-scanning"}},[e._v("Add Servlets, Filters, and Listeners by Using Classpath Scanning")])])])]),e._v(" "),a("h4",{attrs:{id:"_3-10-1-add-a-servlet-filter-or-listener-by-using-a-spring-bean"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-10-1-add-a-servlet-filter-or-listener-by-using-a-spring-bean"}},[e._v("#")]),e._v(" 3.10.1. Add a Servlet, Filter, or Listener by Using a Spring Bean")]),e._v(" "),a("p",[e._v("To add a "),a("code",[e._v("Servlet")]),e._v(", "),a("code",[e._v("Filter")]),e._v(", or servlet "),a("code",[e._v("*Listener")]),e._v(" by using a Spring bean, you must provide a "),a("code",[e._v("@Bean")]),e._v(" definition for it.\nDoing so can be very useful when you want to inject configuration or dependencies.\nHowever, 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.\n(For example, it is not a good idea to have them depend on your "),a("code",[e._v("DataSource")]),e._v(" or JPA configuration.)\nYou can work around such restrictions by initializing the beans lazily when first used instead of on initialization.")]),e._v(" "),a("p",[e._v("In the case of filters and servlets, you can also add mappings and init parameters by adding a "),a("code",[e._v("FilterRegistrationBean")]),e._v(" or a "),a("code",[e._v("ServletRegistrationBean")]),e._v(" instead of or in addition to the underlying component.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If no "),a("code",[e._v("dispatcherType")]),e._v(" is specified on a filter registration, "),a("code",[e._v("REQUEST")]),e._v(" is used."),a("br"),e._v("This aligns with the servlet specification’s default dispatcher type.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Like any other Spring bean, you can define the order of servlet filter beans; please make sure to check the “"),a("RouterLink",{attrs:{to:"/en/spring-boot/web.html#web.servlet.embedded-container.servlets-filters-listeners.beans"}},[e._v("web.html")]),e._v("” section.")],1),e._v(" "),a("h5",{attrs:{id:"disable-registration-of-a-servlet-or-filter"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#disable-registration-of-a-servlet-or-filter"}},[e._v("#")]),e._v(" Disable Registration of a Servlet or Filter")]),e._v(" "),a("p",[e._v("As "),a("a",{attrs:{href:"#howto.webserver.add-servlet-filter-listener.spring-bean"}},[e._v("described earlier")]),e._v(", any "),a("code",[e._v("Servlet")]),e._v(" or "),a("code",[e._v("Filter")]),e._v(" beans are registered with the servlet container automatically.\nTo disable registration of a particular "),a("code",[e._v("Filter")]),e._v(" or "),a("code",[e._v("Servlet")]),e._v(" bean, create a registration bean for it and mark it as disabled, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.web.servlet.FilterRegistrationBean;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyFilterConfiguration {\n\n @Bean\n public FilterRegistrationBean registration(MyFilter filter) {\n FilterRegistrationBean registration = new FilterRegistrationBean<>(filter);\n registration.setEnabled(false);\n return registration;\n }\n\n}\n\n")])])]),a("h4",{attrs:{id:"_3-10-2-add-servlets-filters-and-listeners-by-using-classpath-scanning"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-10-2-add-servlets-filters-and-listeners-by-using-classpath-scanning"}},[e._v("#")]),e._v(" 3.10.2. Add Servlets, Filters, and Listeners by Using Classpath Scanning")]),e._v(" "),a("p",[a("code",[e._v("@WebServlet")]),e._v(", "),a("code",[e._v("@WebFilter")]),e._v(", and "),a("code",[e._v("@WebListener")]),e._v(" annotated classes can be automatically registered with an embedded servlet container by annotating a "),a("code",[e._v("@Configuration")]),e._v(" class with "),a("code",[e._v("@ServletComponentScan")]),e._v(" and specifying the package(s) containing the components that you want to register.\nBy default, "),a("code",[e._v("@ServletComponentScan")]),e._v(" scans from the package of the annotated class.")]),e._v(" "),a("h3",{attrs:{id:"_3-11-configure-access-logging"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-11-configure-access-logging"}},[e._v("#")]),e._v(" 3.11. Configure Access Logging")]),e._v(" "),a("p",[e._v("Access logs can be configured for Tomcat, Undertow, and Jetty through their respective namespaces.")]),e._v(" "),a("p",[e._v("For instance, the following settings log access on Tomcat with a "),a("a",{attrs:{href:"https://tomcat.apache.org/tomcat-9.0-doc/config/valve.html#Access_Logging",target:"_blank",rel:"noopener noreferrer"}},[e._v("custom pattern"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.tomcat.basedir=my-tomcat\nserver.tomcat.accesslog.enabled=true\nserver.tomcat.accesslog.pattern=%t %a %r %s (%D ms)\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n tomcat:\n basedir: "my-tomcat"\n accesslog:\n enabled: true\n pattern: "%t %a %r %s (%D ms)"\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The default location for logs is a "),a("code",[e._v("logs")]),e._v(" directory relative to the Tomcat base directory."),a("br"),e._v("By default, the "),a("code",[e._v("logs")]),e._v(" directory is a temporary directory, so you may want to fix Tomcat’s base directory or use an absolute path for the logs."),a("br"),e._v("In the preceding example, the logs are available in "),a("code",[e._v("my-tomcat/logs")]),e._v(" relative to the working directory of the application.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Access logging for Undertow can be configured in a similar fashion, as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.undertow.accesslog.enabled=true\nserver.undertow.accesslog.pattern=%t %a %r %s (%D ms)\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n undertow:\n accesslog:\n enabled: true\n pattern: "%t %a %r %s (%D ms)"\n')])])]),a("p",[e._v("Logs are stored in a "),a("code",[e._v("logs")]),e._v(" directory relative to the working directory of the application.\nYou can customize this location by setting the "),a("code",[e._v("server.undertow.accesslog.dir")]),e._v(" property.")]),e._v(" "),a("p",[e._v("Finally, access logging for Jetty can also be configured as follows:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.jetty.accesslog.enabled=true\nserver.jetty.accesslog.filename=/var/log/jetty-access.log\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n jetty:\n accesslog:\n enabled: true\n filename: "/var/log/jetty-access.log"\n')])])]),a("p",[e._v("By default, logs are redirected to "),a("code",[e._v("System.err")]),e._v(".\nFor more details, see the Jetty documentation.")]),e._v(" "),a("h3",{attrs:{id:"_3-12-running-behind-a-front-end-proxy-server"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-12-running-behind-a-front-end-proxy-server"}},[e._v("#")]),e._v(" 3.12. Running Behind a Front-end Proxy Server")]),e._v(" "),a("p",[e._v("If your application is running behind a proxy, a load-balancer or in the cloud, the request information (like the host, port, scheme…​) might change along the way.\nYour application may be running on "),a("code",[e._v("10.10.10.10:8080")]),e._v(", but HTTP clients should only see "),a("code",[e._v("example.org")]),e._v(".")]),e._v(" "),a("p",[a("a",{attrs:{href:"https://tools.ietf.org/html/rfc7239",target:"_blank",rel:"noopener noreferrer"}},[e._v('RFC7239 "Forwarded Headers"'),a("OutboundLink")],1),e._v(" defines the "),a("code",[e._v("Forwarded")]),e._v(" HTTP header; proxies can use this header to provide information about the original request.\nYou can configure your application to read those headers and automatically use that information when creating links and sending them to clients in HTTP 302 responses, JSON documents or HTML pages.\nThere are also non-standard headers, like "),a("code",[e._v("X-Forwarded-Host")]),e._v(", "),a("code",[e._v("X-Forwarded-Port")]),e._v(", "),a("code",[e._v("X-Forwarded-Proto")]),e._v(", "),a("code",[e._v("X-Forwarded-Ssl")]),e._v(", and "),a("code",[e._v("X-Forwarded-Prefix")]),e._v(".")]),e._v(" "),a("p",[e._v("If the proxy adds the commonly used "),a("code",[e._v("X-Forwarded-For")]),e._v(" and "),a("code",[e._v("X-Forwarded-Proto")]),e._v(" headers, setting "),a("code",[e._v("server.forward-headers-strategy")]),e._v(" to "),a("code",[e._v("NATIVE")]),e._v(" is enough to support those.\nWith this option, the Web servers themselves natively support this feature; you can check their specific documentation to learn about specific behavior.")]),e._v(" "),a("p",[e._v("If this is not enough, Spring Framework provides a "),a("a",{attrs:{href:"https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#filters-forwarded-headers",target:"_blank",rel:"noopener noreferrer"}},[e._v("ForwardedHeaderFilter"),a("OutboundLink")],1),e._v(".\nYou can register it as a servlet filter in your application by setting "),a("code",[e._v("server.forward-headers-strategy")]),e._v(" is set to "),a("code",[e._v("FRAMEWORK")]),e._v(".")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If you are using Tomcat and terminating SSL at the proxy, "),a("code",[e._v("server.tomcat.redirect-context-root")]),e._v(" should be set to "),a("code",[e._v("false")]),e._v("."),a("br"),e._v("This allows the "),a("code",[e._v("X-Forwarded-Proto")]),e._v(" header to be honored before any redirects are performed.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If your application runs in Cloud Foundry or Heroku, the "),a("code",[e._v("server.forward-headers-strategy")]),e._v(" property defaults to "),a("code",[e._v("NATIVE")]),e._v("."),a("br"),e._v("In all other instances, it defaults to "),a("code",[e._v("NONE")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_3-12-1-customize-tomcat-s-proxy-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-12-1-customize-tomcat-s-proxy-configuration"}},[e._v("#")]),e._v(" 3.12.1. Customize Tomcat’s Proxy Configuration")]),e._v(" "),a("p",[e._v("If you use Tomcat, you can additionally configure the names of the headers used to carry “forwarded” information, as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.tomcat.remoteip.remote-ip-header=x-your-remote-ip-header\nserver.tomcat.remoteip.protocol-header=x-your-protocol-header\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n tomcat:\n remoteip:\n remote-ip-header: "x-your-remote-ip-header"\n protocol-header: "x-your-protocol-header"\n')])])]),a("p",[e._v("Tomcat is also configured with a default regular expression that matches internal proxies that are to be trusted.\nBy default, IP addresses in "),a("code",[e._v("10/8")]),e._v(", "),a("code",[e._v("192.168/16")]),e._v(", "),a("code",[e._v("169.254/16")]),e._v(" and "),a("code",[e._v("127/8")]),e._v(" are trusted.\nYou can customize the valve’s configuration by adding an entry to "),a("code",[e._v("application.properties")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.tomcat.remoteip.internal-proxies=192\\\\.168\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n tomcat:\n remoteip:\n internal-proxies: "192\\\\.168\\\\.\\\\d{1,3}\\\\.\\\\d{1,3}"\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("You can trust all proxies by setting the "),a("code",[e._v("internal-proxies")]),e._v(" to empty (but do not do so in production).")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("You can take complete control of the configuration of Tomcat’s "),a("code",[e._v("RemoteIpValve")]),e._v(" by switching the automatic one off (to do so, set "),a("code",[e._v("server.forward-headers-strategy=NONE")]),e._v(") and adding a new valve instance using a "),a("code",[e._v("WebServerFactoryCustomizer")]),e._v(" bean.")]),e._v(" "),a("h3",{attrs:{id:"_3-13-enable-multiple-connectors-with-tomcat"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-13-enable-multiple-connectors-with-tomcat"}},[e._v("#")]),e._v(" 3.13. Enable Multiple Connectors with Tomcat")]),e._v(" "),a("p",[e._v("You can add an "),a("code",[e._v("org.apache.catalina.connector.Connector")]),e._v(" to the "),a("code",[e._v("TomcatServletWebServerFactory")]),e._v(", which can allow multiple connectors, including HTTP and HTTPS connectors, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import java.io.IOException;\nimport java.net.URL;\n\nimport org.apache.catalina.connector.Connector;\nimport org.apache.coyote.http11.Http11NioProtocol;\n\nimport org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;\nimport org.springframework.boot.web.server.WebServerFactoryCustomizer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.util.ResourceUtils;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyTomcatConfiguration {\n\n @Bean\n public WebServerFactoryCustomizer sslConnectorCustomizer() {\n return (tomcat) -> tomcat.addAdditionalTomcatConnectors(createSslConnector());\n }\n\n private Connector createSslConnector() {\n Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");\n Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();\n try {\n URL keystore = ResourceUtils.getURL("keystore");\n URL truststore = ResourceUtils.getURL("truststore");\n connector.setScheme("https");\n connector.setSecure(true);\n connector.setPort(8443);\n protocol.setSSLEnabled(true);\n protocol.setKeystoreFile(keystore.toString());\n protocol.setKeystorePass("changeit");\n protocol.setTruststoreFile(truststore.toString());\n protocol.setTruststorePass("changeit");\n protocol.setKeyAlias("apitester");\n return connector;\n }\n catch (IOException ex) {\n throw new IllegalStateException("Fail to create ssl connector", ex);\n }\n }\n\n}\n\n')])])]),a("h3",{attrs:{id:"_3-14-use-tomcat-s-legacycookieprocessor"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-14-use-tomcat-s-legacycookieprocessor"}},[e._v("#")]),e._v(" 3.14. Use Tomcat’s LegacyCookieProcessor")]),e._v(" "),a("p",[e._v('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:')]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("java.lang.IllegalArgumentException: An invalid character [32] was present in the Cookie value\n")])])]),a("p",[e._v("If at all possible, you should consider updating your code to only store values compliant with later Cookie specifications.\nIf, however, you cannot change the way that cookies are written, you can instead configure Tomcat to use a "),a("code",[e._v("LegacyCookieProcessor")]),e._v(".\nTo switch to the "),a("code",[e._v("LegacyCookieProcessor")]),e._v(", use an "),a("code",[e._v("WebServerFactoryCustomizer")]),e._v(" bean that adds a "),a("code",[e._v("TomcatContextCustomizer")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.apache.tomcat.util.http.LegacyCookieProcessor;\n\nimport org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;\nimport org.springframework.boot.web.server.WebServerFactoryCustomizer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyLegacyCookieProcessorConfiguration {\n\n @Bean\n public WebServerFactoryCustomizer cookieProcessorCustomizer() {\n return (factory) -> factory\n .addContextCustomizers((context) -> context.setCookieProcessor(new LegacyCookieProcessor()));\n }\n\n}\n\n")])])]),a("h3",{attrs:{id:"_3-15-enable-tomcat-s-mbean-registry"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-15-enable-tomcat-s-mbean-registry"}},[e._v("#")]),e._v(" 3.15. Enable Tomcat’s MBean Registry")]),e._v(" "),a("p",[e._v("Embedded Tomcat’s MBean registry is disabled by default.\nThis minimizes Tomcat’s memory footprint.\nIf you want to use Tomcat’s MBeans, for example so that they can be used by Micrometer to expose metrics, you must use the "),a("code",[e._v("server.tomcat.mbeanregistry.enabled")]),e._v(" property to do so, as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.tomcat.mbeanregistry.enabled=true\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server:\n tomcat:\n mbeanregistry:\n enabled: true\n")])])]),a("h3",{attrs:{id:"_3-16-enable-multiple-listeners-with-undertow"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-16-enable-multiple-listeners-with-undertow"}},[e._v("#")]),e._v(" 3.16. Enable Multiple Listeners with Undertow")]),e._v(" "),a("p",[e._v("Add an "),a("code",[e._v("UndertowBuilderCustomizer")]),e._v(" to the "),a("code",[e._v("UndertowServletWebServerFactory")]),e._v(" and add a listener to the "),a("code",[e._v("Builder")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import io.undertow.Undertow.Builder;\n\nimport org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;\nimport org.springframework.boot.web.server.WebServerFactoryCustomizer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyUndertowConfiguration {\n\n @Bean\n public WebServerFactoryCustomizer undertowListenerCustomizer() {\n return (factory) -> factory.addBuilderCustomizers(this::addHttpListener);\n }\n\n private Builder addHttpListener(Builder builder) {\n return builder.addHttpListener(8080, "0.0.0.0");\n }\n\n}\n\n')])])]),a("h3",{attrs:{id:"_3-17-create-websocket-endpoints-using-serverendpoint"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_3-17-create-websocket-endpoints-using-serverendpoint"}},[e._v("#")]),e._v(" 3.17. Create WebSocket Endpoints Using @ServerEndpoint")]),e._v(" "),a("p",[e._v("If you want to use "),a("code",[e._v("@ServerEndpoint")]),e._v(" in a Spring Boot application that used an embedded container, you must declare a single "),a("code",[e._v("ServerEndpointExporter")]),e._v(" "),a("code",[e._v("@Bean")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.socket.server.standard.ServerEndpointExporter;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyWebSocketConfiguration {\n\n @Bean\n public ServerEndpointExporter serverEndpointExporter() {\n return new ServerEndpointExporter();\n }\n\n}\n\n")])])]),a("p",[e._v("The bean shown in the preceding example registers any "),a("code",[e._v("@ServerEndpoint")]),e._v(" annotated beans with the underlying WebSocket container.\nWhen deployed to a standalone servlet container, this role is performed by a servlet container initializer, and the "),a("code",[e._v("ServerEndpointExporter")]),e._v(" bean is not required.")]),e._v(" "),a("h2",{attrs:{id:"_4-spring-mvc"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-spring-mvc"}},[e._v("#")]),e._v(" 4. Spring MVC")]),e._v(" "),a("p",[e._v("Spring Boot has a number of starters that include Spring MVC.\nNote that some starters include a dependency on Spring MVC rather than include it directly.\nThis section answers common questions about Spring MVC and Spring Boot.")]),e._v(" "),a("h3",{attrs:{id:"_4-1-write-a-json-rest-service"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-1-write-a-json-rest-service"}},[e._v("#")]),e._v(" 4.1. Write a JSON REST Service")]),e._v(" "),a("p",[e._v("Any Spring "),a("code",[e._v("@RestController")]),e._v(" 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:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class MyController {\n\n @RequestMapping("/thing")\n public MyThing thing() {\n return new MyThing();\n }\n\n}\n\n')])])]),a("p",[e._v("As long as "),a("code",[e._v("MyThing")]),e._v(" can be serialized by Jackson2 (true for a normal POJO or Groovy object), then "),a("code",[e._v("[localhost:8080/thing](http://localhost:8080/thing)")]),e._v(" serves a JSON representation of it by default.\nNote that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML.")]),e._v(" "),a("h3",{attrs:{id:"_4-2-write-an-xml-rest-service"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-2-write-an-xml-rest-service"}},[e._v("#")]),e._v(" 4.2. Write an XML REST Service")]),e._v(" "),a("p",[e._v("If you have the Jackson XML extension ("),a("code",[e._v("jackson-dataformat-xml")]),e._v(") on the classpath, you can use it to render XML responses.\nThe previous example that we used for JSON would work.\nTo use the Jackson XML renderer, add the following dependency to your project:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n com.fasterxml.jackson.dataformat\n jackson-dataformat-xml\n\n")])])]),a("p",[e._v("If Jackson’s XML extension is not available and JAXB is available, XML can be rendered with the additional requirement of having "),a("code",[e._v("MyThing")]),e._v(" annotated as "),a("code",[e._v("@XmlRootElement")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import javax.xml.bind.annotation.XmlRootElement;\n\n@XmlRootElement\npublic class MyThing {\n\n private String name;\n\n // getters/setters ...\n\n public String getName() {\n return this.name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n}\n\n")])])]),a("p",[e._v("JAXB is only available out of the box with Java 8.\nIf you use a more recent Java generation, add the following dependency to your project:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n org.glassfish.jaxb\n jaxb-runtime\n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("To get the server to render XML instead of JSON, you might have to send an "),a("code",[e._v("Accept: text/xml")]),e._v(" header (or use a browser).")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_4-3-customize-the-jackson-objectmapper"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-3-customize-the-jackson-objectmapper"}},[e._v("#")]),e._v(" 4.3. Customize the Jackson ObjectMapper")]),e._v(" "),a("p",[e._v("Spring MVC (client and server side) uses "),a("code",[e._v("HttpMessageConverters")]),e._v(" to negotiate content conversion in an HTTP exchange.\nIf Jackson is on the classpath, you already get the default converter(s) provided by "),a("code",[e._v("Jackson2ObjectMapperBuilder")]),e._v(", an instance of which is auto-configured for you.")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("ObjectMapper")]),e._v(" (or "),a("code",[e._v("XmlMapper")]),e._v(" for Jackson XML converter) instance (created by default) has the following customized properties:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("MapperFeature.DEFAULT_VIEW_INCLUSION")]),e._v(" is disabled")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES")]),e._v(" is disabled")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("SerializationFeature.WRITE_DATES_AS_TIMESTAMPS")]),e._v(" is disabled")])])]),e._v(" "),a("p",[e._v("Spring Boot also has some features to make it easier to customize this behavior.")]),e._v(" "),a("p",[e._v("You can configure the "),a("code",[e._v("ObjectMapper")]),e._v(" and "),a("code",[e._v("XmlMapper")]),e._v(" instances by using the environment.\nJackson provides an extensive suite of on/off features that can be used to configure various aspects of its processing.\nThese features are described in six enums (in Jackson) that map onto properties in the environment:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Enum")]),e._v(" "),a("th",[e._v("Property")]),e._v(" "),a("th",[e._v("Values")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("com.fasterxml.jackson.databind.DeserializationFeature")])]),e._v(" "),a("td",[a("code",[e._v("spring.jackson.deserialization.")])]),e._v(" "),a("td",[a("code",[e._v("true")]),e._v(", "),a("code",[e._v("false")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("com.fasterxml.jackson.core.JsonGenerator.Feature")])]),e._v(" "),a("td",[a("code",[e._v("spring.jackson.generator.")])]),e._v(" "),a("td",[a("code",[e._v("true")]),e._v(", "),a("code",[e._v("false")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("com.fasterxml.jackson.databind.MapperFeature")])]),e._v(" "),a("td",[a("code",[e._v("spring.jackson.mapper.")])]),e._v(" "),a("td",[a("code",[e._v("true")]),e._v(", "),a("code",[e._v("false")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("com.fasterxml.jackson.core.JsonParser.Feature")])]),e._v(" "),a("td",[a("code",[e._v("spring.jackson.parser.")])]),e._v(" "),a("td",[a("code",[e._v("true")]),e._v(", "),a("code",[e._v("false")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("com.fasterxml.jackson.databind.SerializationFeature")])]),e._v(" "),a("td",[a("code",[e._v("spring.jackson.serialization.")])]),e._v(" "),a("td",[a("code",[e._v("true")]),e._v(", "),a("code",[e._v("false")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("com.fasterxml.jackson.annotation.JsonInclude.Include")])]),e._v(" "),a("td",[a("code",[e._v("spring.jackson.default-property-inclusion")])]),e._v(" "),a("td",[a("code",[e._v("always")]),e._v(", "),a("code",[e._v("non_null")]),e._v(", "),a("code",[e._v("non_absent")]),e._v(", "),a("code",[e._v("non_default")]),e._v(", "),a("code",[e._v("non_empty")])])])])]),e._v(" "),a("p",[e._v("For example, to enable pretty print, set "),a("code",[e._v("spring.jackson.serialization.indent_output=true")]),e._v(".\nNote that, thanks to the use of "),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.external-config.typesafe-configuration-properties.relaxed-binding"}},[e._v("relaxed binding")]),e._v(", the case of "),a("code",[e._v("indent_output")]),e._v(" does not have to match the case of the corresponding enum constant, which is "),a("code",[e._v("INDENT_OUTPUT")]),e._v(".")],1),e._v(" "),a("p",[e._v("This environment-based configuration is applied to the auto-configured "),a("code",[e._v("Jackson2ObjectMapperBuilder")]),e._v(" bean and applies to any mappers created by using the builder, including the auto-configured "),a("code",[e._v("ObjectMapper")]),e._v(" bean.")]),e._v(" "),a("p",[e._v("The context’s "),a("code",[e._v("Jackson2ObjectMapperBuilder")]),e._v(" can be customized by one or more "),a("code",[e._v("Jackson2ObjectMapperBuilderCustomizer")]),e._v(" beans.\nSuch 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.")]),e._v(" "),a("p",[e._v("Any beans of type "),a("code",[e._v("com.fasterxml.jackson.databind.Module")]),e._v(" are automatically registered with the auto-configured "),a("code",[e._v("Jackson2ObjectMapperBuilder")]),e._v(" and are applied to any "),a("code",[e._v("ObjectMapper")]),e._v(" instances that it creates.\nThis provides a global mechanism for contributing custom modules when you add new features to your application.")]),e._v(" "),a("p",[e._v("If you want to replace the default "),a("code",[e._v("ObjectMapper")]),e._v(" completely, either define a "),a("code",[e._v("@Bean")]),e._v(" of that type and mark it as "),a("code",[e._v("@Primary")]),e._v(" or, if you prefer the builder-based approach, define a "),a("code",[e._v("Jackson2ObjectMapperBuilder")]),e._v(" "),a("code",[e._v("@Bean")]),e._v(".\nNote that, in either case, doing so disables all auto-configuration of the "),a("code",[e._v("ObjectMapper")]),e._v(".")]),e._v(" "),a("p",[e._v("If you provide any "),a("code",[e._v("@Beans")]),e._v(" of type "),a("code",[e._v("MappingJackson2HttpMessageConverter")]),e._v(", they replace the default value in the MVC configuration.\nAlso, a convenience bean of type "),a("code",[e._v("HttpMessageConverters")]),e._v(" is provided (and is always available if you use the default MVC configuration).\nIt has some useful methods to access the default and user-enhanced message converters.")]),e._v(" "),a("p",[e._v("See the “"),a("a",{attrs:{href:"#howto.spring-mvc.customize-responsebody-rendering"}},[e._v("Customize the @ResponseBody Rendering")]),e._v("” section and the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("WebMvcAutoConfiguration")]),a("OutboundLink")],1),e._v(" source code for more details.")]),e._v(" "),a("h3",{attrs:{id:"_4-4-customize-the-responsebody-rendering"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-4-customize-the-responsebody-rendering"}},[e._v("#")]),e._v(" 4.4. Customize the @ResponseBody Rendering")]),e._v(" "),a("p",[e._v("Spring uses "),a("code",[e._v("HttpMessageConverters")]),e._v(" to render "),a("code",[e._v("@ResponseBody")]),e._v(" (or responses from "),a("code",[e._v("@RestController")]),e._v(").\nYou can contribute additional converters by adding beans of the appropriate type in a Spring Boot context.\nIf a bean you add is of a type that would have been included by default anyway (such as "),a("code",[e._v("MappingJackson2HttpMessageConverter")]),e._v(" for JSON conversions), it replaces the default value.\nA convenience bean of type "),a("code",[e._v("HttpMessageConverters")]),e._v(" is provided and is always available if you use the default MVC configuration.\nIt 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 "),a("code",[e._v("RestTemplate")]),e._v(").")]),e._v(" "),a("p",[e._v("As in normal MVC usage, any "),a("code",[e._v("WebMvcConfigurer")]),e._v(" beans that you provide can also contribute converters by overriding the "),a("code",[e._v("configureMessageConverters")]),e._v(" method.\nHowever, unlike with normal MVC, you can supply only additional converters that you need (because Spring Boot uses the same mechanism to contribute its defaults).\nFinally, if you opt out of the Spring Boot default MVC configuration by providing your own "),a("code",[e._v("@EnableWebMvc")]),e._v(" configuration, you can take control completely and do everything manually by using "),a("code",[e._v("getMessageConverters")]),e._v(" from "),a("code",[e._v("WebMvcConfigurationSupport")]),e._v(".")]),e._v(" "),a("p",[e._v("See the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("WebMvcAutoConfiguration")]),a("OutboundLink")],1),e._v(" source code for more details.")]),e._v(" "),a("h3",{attrs:{id:"_4-5-handling-multipart-file-uploads"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-5-handling-multipart-file-uploads"}},[e._v("#")]),e._v(" 4.5. Handling Multipart File Uploads")]),e._v(" "),a("p",[e._v("Spring Boot embraces the servlet 3 "),a("code",[e._v("javax.servlet.http.Part")]),e._v(" API to support uploading files.\nBy 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.\nYou may override these values, the location to which intermediate data is stored (for example, to the "),a("code",[e._v("/tmp")]),e._v(" directory), and the threshold past which data is flushed to disk by using the properties exposed in the "),a("code",[e._v("MultipartProperties")]),e._v(" class.\nFor example, if you want to specify that files be unlimited, set the "),a("code",[e._v("spring.servlet.multipart.max-file-size")]),e._v(" property to "),a("code",[e._v("-1")]),e._v(".")]),e._v(" "),a("p",[e._v("The multipart support is helpful when you want to receive multipart encoded file data as a "),a("code",[e._v("@RequestParam")]),e._v("-annotated parameter of type "),a("code",[e._v("MultipartFile")]),e._v(" in a Spring MVC controller handler method.")]),e._v(" "),a("p",[e._v("See the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/MultipartAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("MultipartAutoConfiguration")]),a("OutboundLink")],1),e._v(" source for more details.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("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.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_4-6-switch-off-the-spring-mvc-dispatcherservlet"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-6-switch-off-the-spring-mvc-dispatcherservlet"}},[e._v("#")]),e._v(" 4.6. Switch Off the Spring MVC DispatcherServlet")]),e._v(" "),a("p",[e._v("By default, all content is served from the root of your application ("),a("code",[e._v("/")]),e._v(").\nIf you would rather map to a different path, you can configure one as follows:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.mvc.servlet.path=/mypath\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n mvc:\n servlet:\n path: "/mypath"\n')])])]),a("p",[e._v("If you have additional servlets you can declare a "),a("code",[e._v("@Bean")]),e._v(" of type "),a("code",[e._v("Servlet")]),e._v(" or "),a("code",[e._v("ServletRegistrationBean")]),e._v(" for each and Spring Boot will register them transparently to the container.\nBecause servlets are registered that way, they can be mapped to a sub-context of the "),a("code",[e._v("DispatcherServlet")]),e._v(" without invoking it.")]),e._v(" "),a("p",[e._v("Configuring the "),a("code",[e._v("DispatcherServlet")]),e._v(" yourself is unusual but if you really need to do it, a "),a("code",[e._v("@Bean")]),e._v(" of type "),a("code",[e._v("DispatcherServletPath")]),e._v(" must be provided as well to provide the path of your custom "),a("code",[e._v("DispatcherServlet")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_4-7-switch-off-the-default-mvc-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-7-switch-off-the-default-mvc-configuration"}},[e._v("#")]),e._v(" 4.7. Switch off the Default MVC Configuration")]),e._v(" "),a("p",[e._v("The easiest way to take complete control over MVC configuration is to provide your own "),a("code",[e._v("@Configuration")]),e._v(" with the "),a("code",[e._v("@EnableWebMvc")]),e._v(" annotation.\nDoing so leaves all MVC configuration in your hands.")]),e._v(" "),a("h3",{attrs:{id:"_4-8-customize-viewresolvers"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_4-8-customize-viewresolvers"}},[e._v("#")]),e._v(" 4.8. Customize ViewResolvers")]),e._v(" "),a("p",[e._v("A "),a("code",[e._v("ViewResolver")]),e._v(" is a core component of Spring MVC, translating view names in "),a("code",[e._v("@Controller")]),e._v(" to actual "),a("code",[e._v("View")]),e._v(" implementations.\nNote that "),a("code",[e._v("ViewResolvers")]),e._v(" are mainly used in UI applications, rather than REST-style services (a "),a("code",[e._v("View")]),e._v(" is not used to render a "),a("code",[e._v("@ResponseBody")]),e._v(").\nThere are many implementations of "),a("code",[e._v("ViewResolver")]),e._v(" to choose from, and Spring on its own is not opinionated about which ones you should use.\nSpring Boot, on the other hand, installs one or two for you, depending on what it finds on the classpath and in the application context.\nThe "),a("code",[e._v("DispatcherServlet")]),e._v(" uses all the resolvers it finds in the application context, trying each one in turn until it gets a result.\nIf you add your own, you have to be aware of the order and in which position your resolver is added.")]),e._v(" "),a("p",[a("code",[e._v("WebMvcAutoConfiguration")]),e._v(" adds the following "),a("code",[e._v("ViewResolvers")]),e._v(" to your context:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("An "),a("code",[e._v("InternalResourceViewResolver")]),e._v(" named ‘defaultViewResolver’.\nThis one locates physical resources that can be rendered by using the "),a("code",[e._v("DefaultServlet")]),e._v(" (including static resources and JSP pages, if you use those).\nIt 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 "),a("code",[e._v("spring.mvc.view.prefix")]),e._v(" and "),a("code",[e._v("spring.mvc.view.suffix")]),e._v(").\nYou can override it by providing a bean of the same type.")])]),e._v(" "),a("li",[a("p",[e._v("A "),a("code",[e._v("BeanNameViewResolver")]),e._v(" named ‘beanNameViewResolver’.\nThis is a useful member of the view resolver chain and picks up any beans with the same name as the "),a("code",[e._v("View")]),e._v(" being resolved.\nIt should not be necessary to override or replace it.")])]),e._v(" "),a("li",[a("p",[e._v("A "),a("code",[e._v("ContentNegotiatingViewResolver")]),e._v(" named ‘viewResolver’ is added only if there "),a("strong",[e._v("are")]),e._v(" actually beans of type "),a("code",[e._v("View")]),e._v(" present.\nThis is a composite resolver, delegating to all the others and attempting to find a match to the ‘Accept’ HTTP header sent by the client.\nThere is a useful "),a("a",{attrs:{href:"https://spring.io/blog/2013/06/03/content-negotiation-using-views",target:"_blank",rel:"noopener noreferrer"}},[e._v("blog about "),a("code",[e._v("ContentNegotiatingViewResolver")]),a("OutboundLink")],1),e._v(" that you might like to study to learn more, and you might also look at the source code for detail.\nYou can switch off the auto-configured "),a("code",[e._v("ContentNegotiatingViewResolver")]),e._v(" by defining a bean named ‘viewResolver’.")])]),e._v(" "),a("li",[a("p",[e._v("If you use Thymeleaf, you also have a "),a("code",[e._v("ThymeleafViewResolver")]),e._v(" named ‘thymeleafViewResolver’.\nIt looks for resources by surrounding the view name with a prefix and suffix.\nThe prefix is "),a("code",[e._v("spring.thymeleaf.prefix")]),e._v(", and the suffix is "),a("code",[e._v("spring.thymeleaf.suffix")]),e._v(".\nThe values of the prefix and suffix default to ‘classpath:/templates/’ and ‘.html’, respectively.\nYou can override "),a("code",[e._v("ThymeleafViewResolver")]),e._v(" by providing a bean of the same name.")])]),e._v(" "),a("li",[a("p",[e._v("If you use FreeMarker, you also have a "),a("code",[e._v("FreeMarkerViewResolver")]),e._v(" named ‘freeMarkerViewResolver’.\nIt looks for resources in a loader path (which is externalized to "),a("code",[e._v("spring.freemarker.templateLoaderPath")]),e._v(" and has a default value of ‘classpath:/templates/’) by surrounding the view name with a prefix and a suffix.\nThe prefix is externalized to "),a("code",[e._v("spring.freemarker.prefix")]),e._v(", and the suffix is externalized to "),a("code",[e._v("spring.freemarker.suffix")]),e._v(".\nThe default values of the prefix and suffix are empty and ‘.ftlh’, respectively.\nYou can override "),a("code",[e._v("FreeMarkerViewResolver")]),e._v(" by providing a bean of the same name.")])]),e._v(" "),a("li",[a("p",[e._v("If you use Groovy templates (actually, if "),a("code",[e._v("groovy-templates")]),e._v(" is on your classpath), you also have a "),a("code",[e._v("GroovyMarkupViewResolver")]),e._v(" named ‘groovyMarkupViewResolver’.\nIt looks for resources in a loader path by surrounding the view name with a prefix and suffix (externalized to "),a("code",[e._v("spring.groovy.template.prefix")]),e._v(" and "),a("code",[e._v("spring.groovy.template.suffix")]),e._v(").\nThe prefix and suffix have default values of ‘classpath:/templates/’ and ‘.tpl’, respectively.\nYou can override "),a("code",[e._v("GroovyMarkupViewResolver")]),e._v(" by providing a bean of the same name.")])]),e._v(" "),a("li",[a("p",[e._v("If you use Mustache, you also have a "),a("code",[e._v("MustacheViewResolver")]),e._v(" named ‘mustacheViewResolver’.\nIt looks for resources by surrounding the view name with a prefix and suffix.\nThe prefix is "),a("code",[e._v("spring.mustache.prefix")]),e._v(", and the suffix is "),a("code",[e._v("spring.mustache.suffix")]),e._v(".\nThe values of the prefix and suffix default to ‘classpath:/templates/’ and ‘.mustache’, respectively.\nYou can override "),a("code",[e._v("MustacheViewResolver")]),e._v(" by providing a bean of the same name.")])])]),e._v(" "),a("p",[e._v("For more detail, see the following sections:")]),e._v(" "),a("ul",[a("li",[a("p",[a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("WebMvcAutoConfiguration")]),a("OutboundLink")],1)])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("ThymeleafAutoConfiguration")]),a("OutboundLink")],1)])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("FreeMarkerAutoConfiguration")]),a("OutboundLink")],1)])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("GroovyTemplateAutoConfiguration")]),a("OutboundLink")],1)])])]),e._v(" "),a("h2",{attrs:{id:"_5-jersey"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-jersey"}},[e._v("#")]),e._v(" 5. Jersey")]),e._v(" "),a("h3",{attrs:{id:"_5-1-secure-jersey-endpoints-with-spring-security"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-1-secure-jersey-endpoints-with-spring-security"}},[e._v("#")]),e._v(" 5.1. Secure Jersey endpoints with Spring Security")]),e._v(" "),a("p",[e._v("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.\nHowever, if you want to use Spring Security’s method-level security with Jersey, you must configure Jersey to use "),a("code",[e._v("setStatus(int)")]),e._v(" rather "),a("code",[e._v("sendError(int)")]),e._v(".\nThis prevents Jersey from committing the response before Spring Security has had an opportunity to report an authentication or authorization failure to the client.")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("jersey.config.server.response.setStatusOverSendError")]),e._v(" property must be set to "),a("code",[e._v("true")]),e._v(" on the application’s "),a("code",[e._v("ResourceConfig")]),e._v(" bean, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import java.util.Collections;\n\nimport org.glassfish.jersey.server.ResourceConfig;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class JerseySetStatusOverSendErrorConfig extends ResourceConfig {\n\n public JerseySetStatusOverSendErrorConfig() {\n register(Endpoint.class);\n setProperties(Collections.singletonMap("jersey.config.server.response.setStatusOverSendError", true));\n }\n\n}\n\n')])])]),a("h3",{attrs:{id:"_5-2-use-jersey-alongside-another-web-framework"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_5-2-use-jersey-alongside-another-web-framework"}},[e._v("#")]),e._v(" 5.2. Use Jersey Alongside Another Web Framework")]),e._v(" "),a("p",[e._v("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.\nFirst, configure Jersey to use a filter rather than a servlet by configuring the "),a("code",[e._v("spring.jersey.type")]),e._v(" application property with a value of "),a("code",[e._v("filter")]),e._v(".\nSecond, configure your "),a("code",[e._v("ResourceConfig")]),e._v(" to forward requests that would have resulted in a 404, as shown in the following example.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.glassfish.jersey.server.ResourceConfig;\nimport org.glassfish.jersey.servlet.ServletProperties;\n\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class JerseyConfig extends ResourceConfig {\n\n public JerseyConfig() {\n register(Endpoint.class);\n property(ServletProperties.FILTER_FORWARD_ON_404, true);\n }\n\n}\n\n")])])]),a("h2",{attrs:{id:"_6-http-clients"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_6-http-clients"}},[e._v("#")]),e._v(" 6. HTTP Clients")]),e._v(" "),a("p",[e._v("Spring Boot offers a number of starters that work with HTTP clients.\nThis section answers questions related to using them.")]),e._v(" "),a("h3",{attrs:{id:"_6-1-configure-resttemplate-to-use-a-proxy"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_6-1-configure-resttemplate-to-use-a-proxy"}},[e._v("#")]),e._v(" 6.1. Configure RestTemplate to Use a Proxy")]),e._v(" "),a("p",[e._v("As described in "),a("RouterLink",{attrs:{to:"/en/spring-boot/io.html#io.rest-client.resttemplate.customization"}},[e._v("io.html")]),e._v(", you can use a "),a("code",[e._v("RestTemplateCustomizer")]),e._v(" with "),a("code",[e._v("RestTemplateBuilder")]),e._v(" to build a customized "),a("code",[e._v("RestTemplate")]),e._v(".\nThis is the recommended approach for creating a "),a("code",[e._v("RestTemplate")]),e._v(" configured to use a proxy.")],1),e._v(" "),a("p",[e._v("The exact details of the proxy configuration depend on the underlying client request factory that is being used.")]),e._v(" "),a("h3",{attrs:{id:"_6-2-configure-the-tcpclient-used-by-a-reactor-netty-based-webclient"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_6-2-configure-the-tcpclient-used-by-a-reactor-netty-based-webclient"}},[e._v("#")]),e._v(" 6.2. Configure the TcpClient used by a Reactor Netty-based WebClient")]),e._v(" "),a("p",[e._v("When Reactor Netty is on the classpath a Reactor Netty-based "),a("code",[e._v("WebClient")]),e._v(" is auto-configured.\nTo customize the client’s handling of network connections, provide a "),a("code",[e._v("ClientHttpConnector")]),e._v(" bean.\nThe following example configures a 60 second connect timeout and adds a "),a("code",[e._v("ReadTimeoutHandler")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import io.netty.channel.ChannelOption;\nimport io.netty.handler.timeout.ReadTimeoutHandler;\nimport reactor.netty.http.client.HttpClient;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.http.client.reactive.ClientHttpConnector;\nimport org.springframework.http.client.reactive.ReactorClientHttpConnector;\nimport org.springframework.http.client.reactive.ReactorResourceFactory;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyReactorNettyClientConfiguration {\n\n @Bean\n ClientHttpConnector clientHttpConnector(ReactorResourceFactory resourceFactory) {\n HttpClient httpClient = HttpClient.create(resourceFactory.getConnectionProvider())\n .runOn(resourceFactory.getLoopResources())\n .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 60000)\n .doOnConnected((connection) -> connection.addHandlerLast(new ReadTimeoutHandler(60)));\n return new ReactorClientHttpConnector(httpClient);\n }\n\n}\n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Note the use of "),a("code",[e._v("ReactorResourceFactory")]),e._v(" for the connection provider and event loop resources."),a("br"),e._v("This ensures efficient sharing of resources for the server receiving requests and the client making requests.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h2",{attrs:{id:"_7-logging"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-logging"}},[e._v("#")]),e._v(" 7. Logging")]),e._v(" "),a("p",[e._v("Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s "),a("code",[e._v("spring-jcl")]),e._v(" module.\nTo use "),a("a",{attrs:{href:"https://logback.qos.ch",target:"_blank",rel:"noopener noreferrer"}},[e._v("Logback"),a("OutboundLink")],1),e._v(", you need to include it and "),a("code",[e._v("spring-jcl")]),e._v(" on the classpath.\nThe recommended way to do that is through the starters, which all depend on "),a("code",[e._v("spring-boot-starter-logging")]),e._v(".\nFor a web application, you need only "),a("code",[e._v("spring-boot-starter-web")]),e._v(", since it depends transitively on the logging starter.\nIf you use Maven, the following dependency adds logging for you:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n org.springframework.boot\n spring-boot-starter-web\n\n")])])]),a("p",[e._v("Spring Boot has a "),a("code",[e._v("LoggingSystem")]),e._v(" abstraction that attempts to configure logging based on the content of the classpath.\nIf Logback is available, it is the first choice.")]),e._v(" "),a("p",[e._v("If the only change you need to make to logging is to set the levels of various loggers, you can do so in "),a("code",[e._v("application.properties")]),e._v(' by using the "logging.level" prefix, as shown in the following example:')]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("logging.level.org.springframework.web=debug\nlogging.level.org.hibernate=error\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('logging:\n level:\n org.springframework.web: "debug"\n org.hibernate: "error"\n')])])]),a("p",[e._v("You can also set the location of a file to which to write the log (in addition to the console) by using "),a("code",[e._v("logging.file.name")]),e._v(".")]),e._v(" "),a("p",[e._v("To configure the more fine-grained settings of a logging system, you need to use the native configuration format supported by the "),a("code",[e._v("LoggingSystem")]),e._v(" in question.\nBy default, Spring Boot picks up the native configuration from its default location for the system (such as "),a("code",[e._v("classpath:logback.xml")]),e._v(" for Logback), but you can set the location of the config file by using the "),a("code",[e._v("logging.config")]),e._v(" property.")]),e._v(" "),a("h3",{attrs:{id:"_7-1-configure-logback-for-logging"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-configure-logback-for-logging"}},[e._v("#")]),e._v(" 7.1. Configure Logback for Logging")]),e._v(" "),a("p",[e._v("If you need to apply customizations to logback beyond those that can be achieved with "),a("code",[e._v("application.properties")]),e._v(", you will need to add a standard logback configuration file.\nYou can add a "),a("code",[e._v("logback.xml")]),e._v(" file to the root of your classpath for logback to find.\nYou can also use "),a("code",[e._v("logback-spring.xml")]),e._v(" if you want to use the "),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.logging.logback-extensions"}},[e._v("Spring Boot Logback extensions")]),e._v(".")],1),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The Logback documentation has a "),a("a",{attrs:{href:"https://logback.qos.ch/manual/configuration.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("dedicated section that covers configuration"),a("OutboundLink")],1),e._v(" in some detail.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Spring Boot provides a number of logback configurations that be "),a("code",[e._v("included")]),e._v(" from your own configuration.\nThese includes are designed to allow certain common Spring Boot conventions to be re-applied.")]),e._v(" "),a("p",[e._v("The following files are provided under "),a("code",[e._v("org/springframework/boot/logging/logback/")]),e._v(":")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("defaults.xml")]),e._v(" - Provides conversion rules, pattern properties and common logger configurations.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("console-appender.xml")]),e._v(" - Adds a "),a("code",[e._v("ConsoleAppender")]),e._v(" using the "),a("code",[e._v("CONSOLE_LOG_PATTERN")]),e._v(".")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("file-appender.xml")]),e._v(" - Adds a "),a("code",[e._v("RollingFileAppender")]),e._v(" using the "),a("code",[e._v("FILE_LOG_PATTERN")]),e._v(" and "),a("code",[e._v("ROLLING_FILE_NAME_PATTERN")]),e._v(" with appropriate settings.")])])]),e._v(" "),a("p",[e._v("In addition, a legacy "),a("code",[e._v("base.xml")]),e._v(" file is provided for compatibility with earlier versions of Spring Boot.")]),e._v(" "),a("p",[e._v("A typical custom "),a("code",[e._v("logback.xml")]),e._v(" file would look something like this:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('\n\n \n \n \n \n \n \n\n')])])]),a("p",[e._v("Your logback configuration file can also make use of System properties that the "),a("code",[e._v("LoggingSystem")]),e._v(" takes care of creating for you:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("${PID}")]),e._v(": The current process ID.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("${LOG_FILE}")]),e._v(": Whether "),a("code",[e._v("logging.file.name")]),e._v(" was set in Boot’s external configuration.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("${LOG_PATH}")]),e._v(": Whether "),a("code",[e._v("logging.file.path")]),e._v(" (representing a directory for log files to live in) was set in Boot’s external configuration.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("${LOG_EXCEPTION_CONVERSION_WORD}")]),e._v(": Whether "),a("code",[e._v("logging.exception-conversion-word")]),e._v(" was set in Boot’s external configuration.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("${ROLLING_FILE_NAME_PATTERN}")]),e._v(": Whether "),a("code",[e._v("logging.pattern.rolling-file-name")]),e._v(" was set in Boot’s external configuration.")])])]),e._v(" "),a("p",[e._v("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.\nSee the "),a("code",[e._v("CONSOLE_LOG_PATTERN")]),e._v(" in the "),a("code",[e._v("defaults.xml")]),e._v(" configuration for an example.")]),e._v(" "),a("p",[e._v("If Groovy is on the classpath, you should be able to configure Logback with "),a("code",[e._v("logback.groovy")]),e._v(" as well.\nIf present, this setting is given preference.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Spring extensions are not supported with Groovy configuration."),a("br"),e._v("Any "),a("code",[e._v("logback-spring.groovy")]),e._v(" files will not be detected.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_7-1-1-configure-logback-for-file-only-output"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-1-1-configure-logback-for-file-only-output"}},[e._v("#")]),e._v(" 7.1.1. Configure Logback for File-only Output")]),e._v(" "),a("p",[e._v("If you want to disable console logging and write output only to a file, you need a custom "),a("code",[e._v("logback-spring.xml")]),e._v(" that imports "),a("code",[e._v("file-appender.xml")]),e._v(" but not "),a("code",[e._v("console-appender.xml")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('\n\n \n \n \n \n \n \n\n')])])]),a("p",[e._v("You also need to add "),a("code",[e._v("logging.file.name")]),e._v(" to your "),a("code",[e._v("application.properties")]),e._v(" or "),a("code",[e._v("application.yaml")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("logging.file.name=myapplication.log\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('logging:\n file:\n name: "myapplication.log"\n')])])]),a("h3",{attrs:{id:"_7-2-configure-log4j-for-logging"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-2-configure-log4j-for-logging"}},[e._v("#")]),e._v(" 7.2. Configure Log4j for Logging")]),e._v(" "),a("p",[e._v("Spring Boot supports "),a("a",{attrs:{href:"https://logging.apache.org/log4j/2.x/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Log4j 2"),a("OutboundLink")],1),e._v(" for logging configuration if it is on the classpath.\nIf you use the starters for assembling dependencies, you have to exclude Logback and then include log4j 2 instead.\nIf you do not use the starters, you need to provide (at least) "),a("code",[e._v("spring-jcl")]),e._v(" in addition to Log4j 2.")]),e._v(" "),a("p",[e._v("The recommended path is through the starters, even though it requires some jiggling.\nThe following example shows how to set up the starters in Maven:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n org.springframework.boot\n spring-boot-starter-web\n\n\n org.springframework.boot\n spring-boot-starter\n \n \n org.springframework.boot\n spring-boot-starter-logging\n \n \n\n\n org.springframework.boot\n spring-boot-starter-log4j2\n\n")])])]),a("p",[e._v("Gradle provides a few different ways to set up the starters.\nOne way is to use a "),a("a",{attrs:{href:"https://docs.gradle.org/current/userguide/resolution_rules.html#sec:module_replacement",target:"_blank",rel:"noopener noreferrer"}},[e._v("module replacement"),a("OutboundLink")],1),e._v(".\nTo do so, declare a dependency on the Log4j 2 starter and tell Gradle that any occurrences of the default logging starter should be replaced by the Log4j 2 starter, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('dependencies {\n implementation "org.springframework.boot:spring-boot-starter-log4j2"\n modules {\n module("org.springframework.boot:spring-boot-starter-logging") {\n replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback")\n }\n }\n}\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The Log4j starters gather together the dependencies for common logging requirements (such as having Tomcat use "),a("code",[e._v("java.util.logging")]),e._v(" but configuring the output using Log4j 2).")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("To ensure that debug logging performed using "),a("code",[e._v("java.util.logging")]),e._v(" is routed into Log4j 2, configure its "),a("a",{attrs:{href:"https://logging.apache.org/log4j/2.x/log4j-jul/index.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("JDK logging adapter"),a("OutboundLink")],1),e._v(" by setting the "),a("code",[e._v("java.util.logging.manager")]),e._v(" system property to "),a("code",[e._v("org.apache.logging.log4j.jul.LogManager")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h4",{attrs:{id:"_7-2-1-use-yaml-or-json-to-configure-log4j-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-2-1-use-yaml-or-json-to-configure-log4j-2"}},[e._v("#")]),e._v(" 7.2.1. Use YAML or JSON to Configure Log4j 2")]),e._v(" "),a("p",[e._v("In addition to its default XML configuration format, Log4j 2 also supports YAML and JSON configuration files.\nTo 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:")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Format")]),e._v(" "),a("th",[e._v("Dependencies")]),e._v(" "),a("th",[e._v("File names")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[e._v("YAML")]),e._v(" "),a("td",[a("code",[e._v("com.fasterxml.jackson.core:jackson-databind")]),e._v(" + "),a("code",[e._v("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml")])]),e._v(" "),a("td",[a("code",[e._v("log4j2.yaml")]),e._v(" + "),a("code",[e._v("log4j2.yml")])])]),e._v(" "),a("tr",[a("td",[e._v("JSON")]),e._v(" "),a("td",[a("code",[e._v("com.fasterxml.jackson.core:jackson-databind")])]),e._v(" "),a("td",[a("code",[e._v("log4j2.json")]),e._v(" + "),a("code",[e._v("log4j2.jsn")])])])])]),e._v(" "),a("h4",{attrs:{id:"_7-2-2-use-composite-configuration-to-configure-log4j-2"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_7-2-2-use-composite-configuration-to-configure-log4j-2"}},[e._v("#")]),e._v(" 7.2.2. Use Composite Configuration to Configure Log4j 2")]),e._v(" "),a("p",[e._v("Log4j 2 has support for combining multiple configuration files into a single composite configuration.\nTo use this support in Spring Boot, configure "),a("code",[e._v("logging.log4j2.config.override")]),e._v(" with the locations of one or more secondary configuration files.\nThe secondary configuration files will be merged with the primary configuration, whether the primary’s source is Spring Boot’s defaults, a standard location such as "),a("code",[e._v("log4j.xml")]),e._v(", or the location configured by the "),a("code",[e._v("logging.config")]),e._v(" property.")]),e._v(" "),a("h2",{attrs:{id:"_8-data-access"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-data-access"}},[e._v("#")]),e._v(" 8. Data Access")]),e._v(" "),a("p",[e._v("Spring Boot includes a number of starters for working with data sources.\nThis section answers questions related to doing so.")]),e._v(" "),a("h3",{attrs:{id:"_8-1-configure-a-custom-datasource"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-1-configure-a-custom-datasource"}},[e._v("#")]),e._v(" 8.1. Configure a Custom DataSource")]),e._v(" "),a("p",[e._v("To configure your own "),a("code",[e._v("DataSource")]),e._v(", define a "),a("code",[e._v("@Bean")]),e._v(" of that type in your configuration.\nSpring Boot reuses your "),a("code",[e._v("DataSource")]),e._v(" anywhere one is required, including database initialization.\nIf you need to externalize some settings, you can bind your "),a("code",[e._v("DataSource")]),e._v(" to the environment (see “"),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.external-config.typesafe-configuration-properties.third-party-configuration"}},[e._v("features.html")]),e._v("”).")],1),e._v(" "),a("p",[e._v("The following example shows how to define a data source in a bean:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyDataSourceConfiguration {\n\n @Bean\n @ConfigurationProperties(prefix = "app.datasource")\n public SomeDataSource dataSource() {\n return new SomeDataSource();\n }\n\n}\n\n')])])]),a("p",[e._v("The following example shows how to define a data source by setting properties:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("app.datasource.url=jdbc:h2:mem:mydb\napp.datasource.username=sa\napp.datasource.pool-size=30\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('app:\n datasource:\n url: "jdbc:h2:mem:mydb"\n username: "sa"\n pool-size: 30\n')])])]),a("p",[e._v("Assuming that "),a("code",[e._v("SomeDataSource")]),e._v(" has regular JavaBean properties for the URL, the username, and the pool size, these settings are bound automatically before the "),a("code",[e._v("DataSource")]),e._v(" is made available to other components.")]),e._v(" "),a("p",[e._v("Spring Boot also provides a utility builder class, called "),a("code",[e._v("DataSourceBuilder")]),e._v(", that can be used to create one of the standard data sources (if it is on the classpath).\nThe builder can detect the one to use based on what is available on the classpath.\nIt also auto-detects the driver based on the JDBC URL.")]),e._v(" "),a("p",[e._v("The following example shows how to create a data source by using a "),a("code",[e._v("DataSourceBuilder")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import javax.sql.DataSource;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.jdbc.DataSourceBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyDataSourceConfiguration {\n\n @Bean\n @ConfigurationProperties("app.datasource")\n public DataSource dataSource() {\n return DataSourceBuilder.create().build();\n }\n\n}\n\n')])])]),a("p",[e._v("To run an app with that "),a("code",[e._v("DataSource")]),e._v(", all you need is the connection information.\nPool-specific settings can also be provided.\nCheck the implementation that is going to be used at runtime for more details.")]),e._v(" "),a("p",[e._v("The following example shows how to define a JDBC data source by setting properties:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("app.datasource.url=jdbc:mysql://localhost/test\napp.datasource.username=dbuser\napp.datasource.password=dbpass\napp.datasource.pool-size=30\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('app:\n datasource:\n url: "jdbc:mysql://localhost/test"\n username: "dbuser"\n password: "dbpass"\n pool-size: 30\n')])])]),a("p",[e._v("However, there is a catch.\nBecause the actual type of the connection pool is not exposed, no keys are generated in the metadata for your custom "),a("code",[e._v("DataSource")]),e._v(" and no completion is available in your IDE (because the "),a("code",[e._v("DataSource")]),e._v(" interface exposes no properties).\nAlso, if you happen to have Hikari on the classpath, this basic setup does not work, because Hikari has no "),a("code",[e._v("url")]),e._v(" property (but does have a "),a("code",[e._v("jdbcUrl")]),e._v(" property).\nIn that case, you must rewrite your configuration as follows:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("app.datasource.jdbc-url=jdbc:mysql://localhost/test\napp.datasource.username=dbuser\napp.datasource.password=dbpass\napp.datasource.pool-size=30\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('app:\n datasource:\n jdbc-url: "jdbc:mysql://localhost/test"\n username: "dbuser"\n password: "dbpass"\n pool-size: 30\n')])])]),a("p",[e._v("You can fix that by forcing the connection pool to use and return a dedicated implementation rather than "),a("code",[e._v("DataSource")]),e._v(".\nYou cannot change the implementation at runtime, but the list of options will be explicit.")]),e._v(" "),a("p",[e._v("The following example shows how create a "),a("code",[e._v("HikariDataSource")]),e._v(" with "),a("code",[e._v("DataSourceBuilder")]),e._v(":")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import com.zaxxer.hikari.HikariDataSource;\n\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.jdbc.DataSourceBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyDataSourceConfiguration {\n\n @Bean\n @ConfigurationProperties("app.datasource")\n public HikariDataSource dataSource() {\n return DataSourceBuilder.create().type(HikariDataSource.class).build();\n }\n\n}\n\n')])])]),a("p",[e._v("You can even go further by leveraging what "),a("code",[e._v("DataSourceProperties")]),e._v(" does for you — that is, by providing a default embedded database with a sensible username and password if no URL is provided.\nYou can easily initialize a "),a("code",[e._v("DataSourceBuilder")]),e._v(" from the state of any "),a("code",[e._v("DataSourceProperties")]),e._v(" object, so you could also inject the DataSource that Spring Boot creates automatically.\nHowever, that would split your configuration into two namespaces: "),a("code",[e._v("url")]),e._v(", "),a("code",[e._v("username")]),e._v(", "),a("code",[e._v("password")]),e._v(", "),a("code",[e._v("type")]),e._v(", and "),a("code",[e._v("driver")]),e._v(" on "),a("code",[e._v("spring.datasource")]),e._v(" and the rest on your custom namespace ("),a("code",[e._v("app.datasource")]),e._v(").\nTo avoid that, you can redefine a custom "),a("code",[e._v("DataSourceProperties")]),e._v(" on your custom namespace, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import com.zaxxer.hikari.HikariDataSource;\n\nimport org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Primary;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyDataSourceConfiguration {\n\n @Bean\n @Primary\n @ConfigurationProperties("app.datasource")\n public DataSourceProperties dataSourceProperties() {\n return new DataSourceProperties();\n }\n\n @Bean\n @ConfigurationProperties("app.datasource.configuration")\n public HikariDataSource dataSource(DataSourceProperties properties) {\n return properties.initializeDataSourceBuilder().type(HikariDataSource.class).build();\n }\n\n}\n\n')])])]),a("p",[e._v("This setup puts you "),a("em",[e._v("in sync")]),e._v(" 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 "),a("code",[e._v("app.datasource.configuration")]),e._v(" sub namespace.\nBecause "),a("code",[e._v("DataSourceProperties")]),e._v(" is taking care of the "),a("code",[e._v("url")]),e._v("/"),a("code",[e._v("jdbcUrl")]),e._v(" translation for you, you can configure it as follows:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("app.datasource.url=jdbc:mysql://localhost/test\napp.datasource.username=dbuser\napp.datasource.password=dbpass\napp.datasource.configuration.maximum-pool-size=30\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('app:\n datasource:\n url: "jdbc:mysql://localhost/test"\n username: "dbuser"\n password: "dbpass"\n configuration:\n maximum-pool-size: 30\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Spring Boot will expose Hikari-specific settings to "),a("code",[e._v("spring.datasource.hikari")]),e._v("."),a("br"),e._v("This example uses a more generic "),a("code",[e._v("configuration")]),e._v(" sub namespace as the example does not support multiple datasource implementations.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Because your custom configuration chooses to go with Hikari, "),a("code",[e._v("app.datasource.type")]),e._v(" has no effect."),a("br"),e._v("In practice, the builder is initialized with whatever value you might set there and then overridden by the call to "),a("code",[e._v(".type()")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("See “"),a("RouterLink",{attrs:{to:"/en/spring-boot/data.html#data.sql.datasource"}},[e._v("data.html")]),e._v("” in the “Spring Boot features” section and the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("DataSourceAutoConfiguration")]),a("OutboundLink")],1),e._v(" class for more details.")],1),e._v(" "),a("h3",{attrs:{id:"_8-2-configure-two-datasources"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-2-configure-two-datasources"}},[e._v("#")]),e._v(" 8.2. Configure Two DataSources")]),e._v(" "),a("p",[e._v("If you need to configure multiple data sources, you can apply the same tricks that are described in the previous section.\nYou must, however, mark one of the "),a("code",[e._v("DataSource")]),e._v(" instances as "),a("code",[e._v("@Primary")]),e._v(", because various auto-configurations down the road expect to be able to get one by type.")]),e._v(" "),a("p",[e._v("If you create your own "),a("code",[e._v("DataSource")]),e._v(", the auto-configuration backs off.\nIn the following example, we provide the "),a("em",[e._v("exact")]),e._v(" same feature set as the auto-configuration provides on the primary data source:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import com.zaxxer.hikari.HikariDataSource;\nimport org.apache.commons.dbcp2.BasicDataSource;\n\nimport org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.jdbc.DataSourceBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Primary;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyDataSourcesConfiguration {\n\n @Bean\n @Primary\n @ConfigurationProperties("app.datasource.first")\n public DataSourceProperties firstDataSourceProperties() {\n return new DataSourceProperties();\n }\n\n @Bean\n @Primary\n @ConfigurationProperties("app.datasource.first.configuration")\n public HikariDataSource firstDataSource(DataSourceProperties firstDataSourceProperties) {\n return firstDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();\n }\n\n @Bean\n @ConfigurationProperties("app.datasource.second")\n public BasicDataSource secondDataSource() {\n return DataSourceBuilder.create().type(BasicDataSource.class).build();\n }\n\n}\n\n')])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[a("code",[e._v("firstDataSourceProperties")]),e._v(" has to be flagged as "),a("code",[e._v("@Primary")]),e._v(" so that the database initializer feature uses your copy (if you use the initializer).")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Both data sources are also bound for advanced customizations.\nFor instance, you could configure them as follows:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("app.datasource.first.url=jdbc:mysql://localhost/first\napp.datasource.first.username=dbuser\napp.datasource.first.password=dbpass\napp.datasource.first.configuration.maximum-pool-size=30\n\napp.datasource.second.url=jdbc:mysql://localhost/second\napp.datasource.second.username=dbuser\napp.datasource.second.password=dbpass\napp.datasource.second.max-total=30\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('app:\n datasource:\n first:\n url: "jdbc:mysql://localhost/first"\n username: "dbuser"\n password: "dbpass"\n configuration:\n maximum-pool-size: 30\n\n second:\n url: "jdbc:mysql://localhost/second"\n username: "dbuser"\n password: "dbpass"\n max-total: 30\n')])])]),a("p",[e._v("You can apply the same concept to the secondary "),a("code",[e._v("DataSource")]),e._v(" as well, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import com.zaxxer.hikari.HikariDataSource;\nimport org.apache.commons.dbcp2.BasicDataSource;\n\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.context.annotation.Primary;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyCompleteDataSourcesConfiguration {\n\n @Bean\n @Primary\n @ConfigurationProperties("app.datasource.first")\n public DataSourceProperties firstDataSourceProperties() {\n return new DataSourceProperties();\n }\n\n @Bean\n @Primary\n @ConfigurationProperties("app.datasource.first.configuration")\n public HikariDataSource firstDataSource(DataSourceProperties firstDataSourceProperties) {\n return firstDataSourceProperties.initializeDataSourceBuilder().type(HikariDataSource.class).build();\n }\n\n @Bean\n @ConfigurationProperties("app.datasource.second")\n public DataSourceProperties secondDataSourceProperties() {\n return new DataSourceProperties();\n }\n\n @Bean\n @ConfigurationProperties("app.datasource.second.configuration")\n public BasicDataSource secondDataSource(\n @Qualifier("secondDataSourceProperties") DataSourceProperties secondDataSourceProperties) {\n return secondDataSourceProperties.initializeDataSourceBuilder().type(BasicDataSource.class).build();\n }\n\n}\n\n')])])]),a("p",[e._v("The preceding example configures two data sources on custom namespaces with the same logic as Spring Boot would use in auto-configuration.\nNote that each "),a("code",[e._v("configuration")]),e._v(" sub namespace provides advanced settings based on the chosen implementation.")]),e._v(" "),a("h3",{attrs:{id:"_8-3-use-spring-data-repositories"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-3-use-spring-data-repositories"}},[e._v("#")]),e._v(" 8.3. Use Spring Data Repositories")]),e._v(" "),a("p",[e._v("Spring Data can create implementations of "),a("code",[e._v("@Repository")]),e._v(" interfaces of various flavors.\nSpring Boot handles all of that for you, as long as those "),a("code",[e._v("@Repositories")]),e._v(" are included in the same package (or a sub-package) of your "),a("code",[e._v("@EnableAutoConfiguration")]),e._v(" class.")]),e._v(" "),a("p",[e._v("For many applications, all you need is to put the right Spring Data dependencies on your classpath.\nThere is a "),a("code",[e._v("spring-boot-starter-data-jpa")]),e._v(" for JPA, "),a("code",[e._v("spring-boot-starter-data-mongodb")]),e._v(" for Mongodb, and various other starters for supported technologies.\nTo get started, create some repository interfaces to handle your "),a("code",[e._v("@Entity")]),e._v(" objects.")]),e._v(" "),a("p",[e._v("Spring Boot tries to guess the location of your "),a("code",[e._v("@Repository")]),e._v(" definitions, based on the "),a("code",[e._v("@EnableAutoConfiguration")]),e._v(" it finds.\nTo get more control, use the "),a("code",[e._v("@EnableJpaRepositories")]),e._v(" annotation (from Spring Data JPA).")]),e._v(" "),a("p",[e._v("For more about Spring Data, see the "),a("a",{attrs:{href:"https://spring.io/projects/spring-data",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Data project page"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_8-4-separate-entity-definitions-from-spring-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-4-separate-entity-definitions-from-spring-configuration"}},[e._v("#")]),e._v(" 8.4. Separate @Entity Definitions from Spring Configuration")]),e._v(" "),a("p",[e._v("Spring Boot tries to guess the location of your "),a("code",[e._v("@Entity")]),e._v(" definitions, based on the "),a("code",[e._v("@EnableAutoConfiguration")]),e._v(" it finds.\nTo get more control, you can use the "),a("code",[e._v("@EntityScan")]),e._v(" annotation, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.autoconfigure.EnableAutoConfiguration;\nimport org.springframework.boot.autoconfigure.domain.EntityScan;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\n@EnableAutoConfiguration\n@EntityScan(basePackageClasses = City.class)\npublic class MyApplication {\n\n // ...\n\n}\n\n")])])]),a("h3",{attrs:{id:"_8-5-configure-jpa-properties"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-5-configure-jpa-properties"}},[e._v("#")]),e._v(" 8.5. Configure JPA Properties")]),e._v(" "),a("p",[e._v("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.\nSome of them are automatically detected according to the context so you should not have to set them.")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("spring.jpa.hibernate.ddl-auto")]),e._v(" is a special case, because, depending on runtime conditions, it has different defaults.\nIf an embedded database is used and no schema manager (such as Liquibase or Flyway) is handling the "),a("code",[e._v("DataSource")]),e._v(", it defaults to "),a("code",[e._v("create-drop")]),e._v(".\nIn all other cases, it defaults to "),a("code",[e._v("none")]),e._v(".")]),e._v(" "),a("p",[e._v("The dialect to use is detected by the JPA provider.\nIf you prefer to set the dialect yourself, set the "),a("code",[e._v("spring.jpa.database-platform")]),e._v(" property.")]),e._v(" "),a("p",[e._v("The most common options to set are shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.jpa.hibernate.naming.physical-strategy=com.example.MyPhysicalNamingStrategy\nspring.jpa.show-sql=true\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n jpa:\n hibernate:\n naming:\n physical-strategy: "com.example.MyPhysicalNamingStrategy"\n show-sql: true\n')])])]),a("p",[e._v("In addition, all properties in "),a("code",[e._v("spring.jpa.properties.*")]),e._v(" are passed through as normal JPA properties (with the prefix stripped) when the local "),a("code",[e._v("EntityManagerFactory")]),e._v(" is created.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("You need to ensure that names defined under "),a("code",[e._v("spring.jpa.properties.*")]),e._v(" exactly match those expected by your JPA provider."),a("br"),e._v("Spring Boot will not attempt any kind of relaxed binding for these entries."),a("br"),a("br"),e._v("For example, if you want to configure Hibernate’s batch size you must use "),a("code",[e._v("spring.jpa.properties.hibernate.jdbc.batch_size")]),e._v("."),a("br"),e._v("If you use other forms, such as "),a("code",[e._v("batchSize")]),e._v(" or "),a("code",[e._v("batch-size")]),e._v(", Hibernate will not apply the setting.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If you need to apply advanced customization to Hibernate properties, consider registering a "),a("code",[e._v("HibernatePropertiesCustomizer")]),e._v(" bean that will be invoked prior to creating the "),a("code",[e._v("EntityManagerFactory")]),e._v("."),a("br"),e._v("This takes precedence to anything that is applied by the auto-configuration.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_8-6-configure-hibernate-naming-strategy"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-6-configure-hibernate-naming-strategy"}},[e._v("#")]),e._v(" 8.6. Configure Hibernate Naming Strategy")]),e._v(" "),a("p",[e._v("Hibernate uses "),a("a",{attrs:{href:"https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#naming",target:"_blank",rel:"noopener noreferrer"}},[e._v("two different naming strategies"),a("OutboundLink")],1),e._v(" to map names from the object model to the corresponding database names.\nThe fully qualified class name of the physical and the implicit strategy implementations can be configured by setting the "),a("code",[e._v("spring.jpa.hibernate.naming.physical-strategy")]),e._v(" and "),a("code",[e._v("spring.jpa.hibernate.naming.implicit-strategy")]),e._v(" properties, respectively.\nAlternatively, if "),a("code",[e._v("ImplicitNamingStrategy")]),e._v(" or "),a("code",[e._v("PhysicalNamingStrategy")]),e._v(" beans are available in the application context, Hibernate will be automatically configured to use them.")]),e._v(" "),a("p",[e._v("By default, Spring Boot configures the physical naming strategy with "),a("code",[e._v("CamelCaseToUnderscoresNamingStrategy")]),e._v(".\nUsing this strategy, all dots are replaced by underscores and camel casing is replaced by underscores as well.\nAdditionally, by default, all table names are generated in lower case.\nFor example, a "),a("code",[e._v("TelephoneNumber")]),e._v(" entity is mapped to the "),a("code",[e._v("telephone_number")]),e._v(" table.\nIf your schema requires mixed-case identifiers, define a custom "),a("code",[e._v("CamelCaseToUnderscoresNamingStrategy")]),e._v(" bean, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy;\nimport org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyHibernateConfiguration {\n\n @Bean\n public CamelCaseToUnderscoresNamingStrategy caseSensitivePhysicalNamingStrategy() {\n return new CamelCaseToUnderscoresNamingStrategy() {\n\n @Override\n protected boolean isCaseInsensitive(JdbcEnvironment jdbcEnvironment) {\n return false;\n }\n\n };\n }\n\n}\n\n")])])]),a("p",[e._v("If you prefer to use Hibernate 5’s default instead, set the following property:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl\n")])])]),a("p",[e._v("Alternatively, you can configure the following bean:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl;\n\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\nclass MyHibernateConfiguration {\n\n @Bean\n PhysicalNamingStrategyStandardImpl caseSensitivePhysicalNamingStrategy() {\n return new PhysicalNamingStrategyStandardImpl();\n }\n\n}\n\n")])])]),a("p",[e._v("See "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("HibernateJpaAutoConfiguration")]),a("OutboundLink")],1),e._v(" and "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("JpaBaseConfiguration")]),a("OutboundLink")],1),e._v(" for more details.")]),e._v(" "),a("h3",{attrs:{id:"_8-7-configure-hibernate-second-level-caching"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-7-configure-hibernate-second-level-caching"}},[e._v("#")]),e._v(" 8.7. Configure Hibernate Second-Level Caching")]),e._v(" "),a("p",[e._v("Hibernate "),a("a",{attrs:{href:"https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#caching",target:"_blank",rel:"noopener noreferrer"}},[e._v("second-level cache"),a("OutboundLink")],1),e._v(" can be configured for a range of cache providers.\nRather than configuring Hibernate to lookup the cache provider again, it is better to provide the one that is available in the context whenever possible.")]),e._v(" "),a("p",[e._v("To do this with JCache, first make sure that "),a("code",[e._v("org.hibernate:hibernate-jcache")]),e._v(" is available on the classpath.\nThen, add a "),a("code",[e._v("HibernatePropertiesCustomizer")]),e._v(" bean as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.hibernate.cache.jcache.ConfigSettings;\n\nimport org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;\nimport org.springframework.cache.jcache.JCacheCacheManager;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyHibernateSecondLevelCacheConfiguration {\n\n @Bean\n public HibernatePropertiesCustomizer hibernateSecondLevelCacheCustomizer(JCacheCacheManager cacheManager) {\n return (properties) -> properties.put(ConfigSettings.CACHE_MANAGER, cacheManager.getCacheManager());\n }\n\n}\n\n")])])]),a("p",[e._v("This customizer will configure Hibernate to use the same "),a("code",[e._v("CacheManager")]),e._v(" as the one that the application uses.\nIt is also possible to use separate "),a("code",[e._v("CacheManager")]),e._v(" instances.\nFor details, see "),a("a",{attrs:{href:"https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#caching-provider-jcache",target:"_blank",rel:"noopener noreferrer"}},[e._v("the Hibernate user guide"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_8-8-use-dependency-injection-in-hibernate-components"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-8-use-dependency-injection-in-hibernate-components"}},[e._v("#")]),e._v(" 8.8. Use Dependency Injection in Hibernate Components")]),e._v(" "),a("p",[e._v("By default, Spring Boot registers a "),a("code",[e._v("BeanContainer")]),e._v(" implementation that uses the "),a("code",[e._v("BeanFactory")]),e._v(" so that converters and entity listeners can use regular dependency injection.")]),e._v(" "),a("p",[e._v("You can disable or tune this behavior by registering a "),a("code",[e._v("HibernatePropertiesCustomizer")]),e._v(" that removes or changes the "),a("code",[e._v("hibernate.resource.beans.container")]),e._v(" property.")]),e._v(" "),a("h3",{attrs:{id:"_8-9-use-a-custom-entitymanagerfactory"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-9-use-a-custom-entitymanagerfactory"}},[e._v("#")]),e._v(" 8.9. Use a Custom EntityManagerFactory")]),e._v(" "),a("p",[e._v("To take full control of the configuration of the "),a("code",[e._v("EntityManagerFactory")]),e._v(", you need to add a "),a("code",[e._v("@Bean")]),e._v(" named ‘entityManagerFactory’.\nSpring Boot auto-configuration switches off its entity manager in the presence of a bean of that type.")]),e._v(" "),a("h3",{attrs:{id:"_8-10-using-multiple-entitymanagerfactories"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-10-using-multiple-entitymanagerfactories"}},[e._v("#")]),e._v(" 8.10. Using Multiple EntityManagerFactories")]),e._v(" "),a("p",[e._v("If you need to use JPA against multiple data sources, you likely need one "),a("code",[e._v("EntityManagerFactory")]),e._v(" per data source.\nThe "),a("code",[e._v("LocalContainerEntityManagerFactoryBean")]),e._v(" from Spring ORM allows you to configure an "),a("code",[e._v("EntityManagerFactory")]),e._v(" for your needs.\nYou can also reuse "),a("code",[e._v("JpaProperties")]),e._v(" to bind settings for each "),a("code",[e._v("EntityManagerFactory")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import javax.sql.DataSource;\n\nimport org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;\nimport org.springframework.boot.context.properties.ConfigurationProperties;\nimport org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.orm.jpa.JpaVendorAdapter;\nimport org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;\nimport org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyEntityManagerFactoryConfiguration {\n\n @Bean\n @ConfigurationProperties("app.jpa.first")\n public JpaProperties firstJpaProperties() {\n return new JpaProperties();\n }\n\n @Bean\n public LocalContainerEntityManagerFactoryBean firstEntityManagerFactory(DataSource firstDataSource,\n JpaProperties firstJpaProperties) {\n EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(firstJpaProperties);\n return builder.dataSource(firstDataSource).packages(Order.class).persistenceUnit("firstDs").build();\n }\n\n private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties jpaProperties) {\n JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(jpaProperties);\n return new EntityManagerFactoryBuilder(jpaVendorAdapter, jpaProperties.getProperties(), null);\n }\n\n private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {\n // ... map JPA properties as needed\n return new HibernateJpaVendorAdapter();\n }\n\n}\n\n')])])]),a("p",[e._v("The example above creates an "),a("code",[e._v("EntityManagerFactory")]),e._v(" using a "),a("code",[e._v("DataSource")]),e._v(" bean named "),a("code",[e._v("firstDataSource")]),e._v(".\nIt scans entities located in the same package as "),a("code",[e._v("Order")]),e._v(".\nIt is possible to map additional JPA properties using the "),a("code",[e._v("app.first.jpa")]),e._v(" namespace.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("When you create a bean for "),a("code",[e._v("LocalContainerEntityManagerFactoryBean")]),e._v(" yourself, any customization that was applied during the creation of the auto-configured "),a("code",[e._v("LocalContainerEntityManagerFactoryBean")]),e._v(" is lost."),a("br"),e._v("For example, in case of Hibernate, any properties under the "),a("code",[e._v("spring.jpa.hibernate")]),e._v(" prefix will not be automatically applied to your "),a("code",[e._v("LocalContainerEntityManagerFactoryBean")]),e._v("."),a("br"),e._v("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 "),a("code",[e._v("LocalContainerEntityManagerFactoryBean")]),e._v(" bean.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("You should provide a similar configuration for any additional data sources for which you need JPA access.\nTo complete the picture, you need to configure a "),a("code",[e._v("JpaTransactionManager")]),e._v(" for each "),a("code",[e._v("EntityManagerFactory")]),e._v(" as well.\nAlternatively, you might be able to use a JTA transaction manager that spans both.")]),e._v(" "),a("p",[e._v("If you use Spring Data, you need to configure "),a("code",[e._v("@EnableJpaRepositories")]),e._v(" accordingly, as shown in the following examples:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.context.annotation.Configuration;\nimport org.springframework.data.jpa.repository.config.EnableJpaRepositories;\n\n@Configuration(proxyBeanMethods = false)\n@EnableJpaRepositories(basePackageClasses = Order.class, entityManagerFactoryRef = "firstEntityManagerFactory")\npublic class OrderConfiguration {\n\n}\n\n')])])]),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.context.annotation.Configuration;\nimport org.springframework.data.jpa.repository.config.EnableJpaRepositories;\n\n@Configuration(proxyBeanMethods = false)\n@EnableJpaRepositories(basePackageClasses = Customer.class, entityManagerFactoryRef = "secondEntityManagerFactory")\npublic class CustomerConfiguration {\n\n}\n\n')])])]),a("h3",{attrs:{id:"_8-11-use-a-traditional-persistence-xml-file"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-11-use-a-traditional-persistence-xml-file"}},[e._v("#")]),e._v(" 8.11. Use a Traditional persistence.xml File")]),e._v(" "),a("p",[e._v("Spring Boot will not search for or use a "),a("code",[e._v("META-INF/persistence.xml")]),e._v(" by default.\nIf you prefer to use a traditional "),a("code",[e._v("persistence.xml")]),e._v(", you need to define your own "),a("code",[e._v("@Bean")]),e._v(" of type "),a("code",[e._v("LocalEntityManagerFactoryBean")]),e._v(" (with an ID of ‘entityManagerFactory’) and set the persistence unit name there.")]),e._v(" "),a("p",[e._v("See "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/orm/jpa/JpaBaseConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("JpaBaseConfiguration")]),a("OutboundLink")],1),e._v(" for the default settings.")]),e._v(" "),a("h3",{attrs:{id:"_8-12-use-spring-data-jpa-and-mongo-repositories"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-12-use-spring-data-jpa-and-mongo-repositories"}},[e._v("#")]),e._v(" 8.12. Use Spring Data JPA and Mongo Repositories")]),e._v(" "),a("p",[e._v("Spring Data JPA and Spring Data Mongo can both automatically create "),a("code",[e._v("Repository")]),e._v(" implementations for you.\nIf they are both present on the classpath, you might have to do some extra configuration to tell Spring Boot which repositories to create.\nThe most explicit way to do that is to use the standard Spring Data "),a("code",[e._v("@EnableJpaRepositories")]),e._v(" and "),a("code",[e._v("@EnableMongoRepositories")]),e._v(" annotations and provide the location of your "),a("code",[e._v("Repository")]),e._v(" interfaces.")]),e._v(" "),a("p",[e._v("There are also flags ("),a("code",[e._v("spring.data.*.repositories.enabled")]),e._v(" and "),a("code",[e._v("spring.data.*.repositories.type")]),e._v(") that you can use to switch the auto-configured repositories on and off in external configuration.\nDoing so is useful, for instance, in case you want to switch off the Mongo repositories and still use the auto-configured "),a("code",[e._v("MongoTemplate")]),e._v(".")]),e._v(" "),a("p",[e._v("The same obstacle and the same features exist for other auto-configured Spring Data repository types (Elasticsearch, Solr, and others).\nTo work with them, change the names of the annotations and flags accordingly.")]),e._v(" "),a("h3",{attrs:{id:"_8-13-customize-spring-data-s-web-support"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-13-customize-spring-data-s-web-support"}},[e._v("#")]),e._v(" 8.13. Customize Spring Data’s Web Support")]),e._v(" "),a("p",[e._v("Spring Data provides web support that simplifies the use of Spring Data repositories in a web application.\nSpring Boot provides properties in the "),a("code",[e._v("spring.data.web")]),e._v(" namespace for customizing its configuration.\nNote that if you are using Spring Data REST, you must use the properties in the "),a("code",[e._v("spring.data.rest")]),e._v(" namespace instead.")]),e._v(" "),a("h3",{attrs:{id:"_8-14-expose-spring-data-repositories-as-rest-endpoint"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-14-expose-spring-data-repositories-as-rest-endpoint"}},[e._v("#")]),e._v(" 8.14. Expose Spring Data Repositories as REST Endpoint")]),e._v(" "),a("p",[e._v("Spring Data REST can expose the "),a("code",[e._v("Repository")]),e._v(" implementations as REST endpoints for you,\nprovided Spring MVC has been enabled for the application.")]),e._v(" "),a("p",[e._v("Spring Boot exposes a set of useful properties (from the "),a("code",[e._v("spring.data.rest")]),e._v(" namespace) that customize the "),a("a",{attrs:{href:"https://docs.spring.io/spring-data/rest/docs/3.6.2/api/org/springframework/data/rest/core/config/RepositoryRestConfiguration.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("RepositoryRestConfiguration")]),a("OutboundLink")],1),e._v(".\nIf you need to provide additional customization, you should use a "),a("a",{attrs:{href:"https://docs.spring.io/spring-data/rest/docs/3.6.2/api/org/springframework/data/rest/webmvc/config/RepositoryRestConfigurer.html",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("RepositoryRestConfigurer")]),a("OutboundLink")],1),e._v(" bean.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("If you do not specify any order on your custom "),a("code",[e._v("RepositoryRestConfigurer")]),e._v(", it runs after the one Spring Boot uses internally."),a("br"),e._v("If you need to specify an order, make sure it is higher than 0.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_8-15-configure-a-component-that-is-used-by-jpa"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-15-configure-a-component-that-is-used-by-jpa"}},[e._v("#")]),e._v(" 8.15. Configure a Component that is Used by JPA")]),e._v(" "),a("p",[e._v("If you want to configure a component that JPA uses, then you need to ensure that the component is initialized before JPA.\nWhen the component is auto-configured, Spring Boot takes care of this for you.\nFor 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.")]),e._v(" "),a("p",[e._v("If you are configuring a component yourself, you can use an "),a("code",[e._v("EntityManagerFactoryDependsOnPostProcessor")]),e._v(" subclass as a convenient way of setting up the necessary dependencies.\nFor example, if you use Hibernate Search with Elasticsearch as its index manager, any "),a("code",[e._v("EntityManagerFactory")]),e._v(" beans must be configured to depend on the "),a("code",[e._v("elasticsearchClient")]),e._v(" bean, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import javax.persistence.EntityManagerFactory;\n\nimport org.springframework.boot.autoconfigure.orm.jpa.EntityManagerFactoryDependsOnPostProcessor;\nimport org.springframework.stereotype.Component;\n\n/**\n * {@link EntityManagerFactoryDependsOnPostProcessor} that ensures that\n * {@link EntityManagerFactory} beans depend on the {@code elasticsearchClient} bean.\n */\n@Component\npublic class ElasticsearchEntityManagerFactoryDependsOnPostProcessor\n extends EntityManagerFactoryDependsOnPostProcessor {\n\n public ElasticsearchEntityManagerFactoryDependsOnPostProcessor() {\n super("elasticsearchClient");\n }\n\n}\n\n')])])]),a("h3",{attrs:{id:"_8-16-configure-jooq-with-two-datasources"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_8-16-configure-jooq-with-two-datasources"}},[e._v("#")]),e._v(" 8.16. Configure jOOQ with Two DataSources")]),e._v(" "),a("p",[e._v("If you need to use jOOQ with multiple data sources, you should create your own "),a("code",[e._v("DSLContext")]),e._v(" for each one.\nSee "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/jooq/JooqAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[e._v("JooqAutoConfiguration"),a("OutboundLink")],1),e._v(" for more details.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("In particular, "),a("code",[e._v("JooqExceptionTranslator")]),e._v(" and "),a("code",[e._v("SpringTransactionProvider")]),e._v(" can be reused to provide similar features to what the auto-configuration does with a single "),a("code",[e._v("DataSource")]),e._v(".")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h2",{attrs:{id:"_9-database-initialization"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-database-initialization"}},[e._v("#")]),e._v(" 9. Database Initialization")]),e._v(" "),a("p",[e._v("An SQL database can be initialized in different ways depending on what your stack is.\nOf course, you can also do it manually, provided the database is a separate process.\nIt is recommended to use a single mechanism for schema generation.")]),e._v(" "),a("h3",{attrs:{id:"_9-1-initialize-a-database-using-jpa"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-1-initialize-a-database-using-jpa"}},[e._v("#")]),e._v(" 9.1. Initialize a Database Using JPA")]),e._v(" "),a("p",[e._v("JPA has features for DDL generation, and these can be set up to run on startup against the database.\nThis is controlled through two external properties:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("spring.jpa.generate-ddl")]),e._v(" (boolean) switches the feature on and off and is vendor independent.")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("spring.jpa.hibernate.ddl-auto")]),e._v(" (enum) is a Hibernate feature that controls the behavior in a more fine-grained way.\nThis feature is described in more detail later in this guide.")])])]),e._v(" "),a("h3",{attrs:{id:"_9-2-initialize-a-database-using-hibernate"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-2-initialize-a-database-using-hibernate"}},[e._v("#")]),e._v(" 9.2. Initialize a Database Using Hibernate")]),e._v(" "),a("p",[e._v("You can set "),a("code",[e._v("spring.jpa.hibernate.ddl-auto")]),e._v(" explicitly and the standard Hibernate property values are "),a("code",[e._v("none")]),e._v(", "),a("code",[e._v("validate")]),e._v(", "),a("code",[e._v("update")]),e._v(", "),a("code",[e._v("create")]),e._v(", and "),a("code",[e._v("create-drop")]),e._v(".\nSpring Boot chooses a default value for you based on whether it thinks your database is embedded.\nIt defaults to "),a("code",[e._v("create-drop")]),e._v(" if no schema manager has been detected or "),a("code",[e._v("none")]),e._v(" in all other cases.\nAn embedded database is detected by looking at the "),a("code",[e._v("Connection")]),e._v(" type and JDBC url."),a("code",[e._v("hsqldb")]),e._v(", "),a("code",[e._v("h2")]),e._v(", and "),a("code",[e._v("derby")]),e._v(" are candidates, and others are not.\nBe 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.\nYou either have to set "),a("code",[e._v("ddl-auto")]),e._v(" explicitly or use one of the other mechanisms to initialize the database.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("You can output the schema creation by enabling the "),a("code",[e._v("org.hibernate.SQL")]),e._v(" logger."),a("br"),e._v("This is done for you automatically if you enable the "),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.logging.console-output"}},[e._v("debug mode")]),e._v(".")],1)])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("In addition, a file named "),a("code",[e._v("import.sql")]),e._v(" in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the "),a("code",[e._v("ddl-auto")]),e._v(" property is set to "),a("code",[e._v("create")]),e._v(" or "),a("code",[e._v("create-drop")]),e._v(").\nThis 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.\nIt is a Hibernate feature (and has nothing to do with Spring).")]),e._v(" "),a("h3",{attrs:{id:"_9-3-initialize-a-database-using-basic-sql-scripts"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-3-initialize-a-database-using-basic-sql-scripts"}},[e._v("#")]),e._v(" 9.3. Initialize a Database Using Basic SQL Scripts")]),e._v(" "),a("p",[e._v("Spring Boot can automatically create the schema (DDL scripts) of your JDBC "),a("code",[e._v("DataSource")]),e._v(" or R2DBC "),a("code",[e._v("ConnectionFactory")]),e._v(" and initialize it (DML scripts).\nIt loads SQL from the standard root classpath locations: "),a("code",[e._v("schema.sql")]),e._v(" and "),a("code",[e._v("data.sql")]),e._v(", respectively.\nIn addition, Spring Boot processes the "),a("code",[e._v("schema-${platform}.sql")]),e._v(" and "),a("code",[e._v("data-${platform}.sql")]),e._v(" files (if present), where "),a("code",[e._v("platform")]),e._v(" is the value of "),a("code",[e._v("spring.sql.init.platform")]),e._v(".\nThis allows you to switch to database-specific scripts if necessary.\nFor example, you might choose to set it to the vendor name of the database ("),a("code",[e._v("hsqldb")]),e._v(", "),a("code",[e._v("h2")]),e._v(", "),a("code",[e._v("oracle")]),e._v(", "),a("code",[e._v("mysql")]),e._v(", "),a("code",[e._v("postgresql")]),e._v(", and so on).\nBy default, SQL database initialization is only performed when using an embedded in-memory database.\nTo always initialize an SQL database, irrespective of its type, set "),a("code",[e._v("spring.sql.init.mode")]),e._v(" to "),a("code",[e._v("always")]),e._v(".\nSimilarly, to disable initialization, set "),a("code",[e._v("spring.sql.init.mode")]),e._v(" to "),a("code",[e._v("never")]),e._v(".\nBy default, Spring Boot enables the fail-fast feature of its script-based database initializer.\nThis means that, if the scripts cause exceptions, the application fails to start.\nYou can tune that behavior by setting "),a("code",[e._v("spring.sql.init.continue-on-error")]),e._v(".")]),e._v(" "),a("p",[e._v("Script-based "),a("code",[e._v("DataSource")]),e._v(" initialization is performed, by default, before any JPA "),a("code",[e._v("EntityManagerFactory")]),e._v(" beans are created."),a("code",[e._v("schema.sql")]),e._v(" can be used to create the schema for JPA-managed entities and "),a("code",[e._v("data.sql")]),e._v(" can be used to populate it.\nWhile we do not recommend using multiple data source initialization technologies, if you want script-based "),a("code",[e._v("DataSource")]),e._v(" initialization to be able to build upon the schema creation performed by Hibernate, set "),a("code",[e._v("spring.jpa.defer-datasource-initialization")]),e._v(" to "),a("code",[e._v("true")]),e._v(".\nThis will defer data source initialization until after any "),a("code",[e._v("EntityManagerFactory")]),e._v(" beans have been created and initialized."),a("code",[e._v("schema.sql")]),e._v(" can then be used to make additions to any schema creation performed by Hibernate and "),a("code",[e._v("data.sql")]),e._v(" can be used to populate it.")]),e._v(" "),a("p",[e._v("If you are using a "),a("a",{attrs:{href:"#howto.data-initialization.migration-tool"}},[e._v("Higher-level Database Migration Tool")]),e._v(", like Flyway or Liquibase, you should use them alone to create and initialize the schema.\nUsing the basic "),a("code",[e._v("schema.sql")]),e._v(" and "),a("code",[e._v("data.sql")]),e._v(" scripts alongside Flyway or Liquibase is not recommended and support will be removed in a future release.")]),e._v(" "),a("h3",{attrs:{id:"_9-4-initialize-a-spring-batch-database"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-4-initialize-a-spring-batch-database"}},[e._v("#")]),e._v(" 9.4. Initialize a Spring Batch Database")]),e._v(" "),a("p",[e._v("If you use Spring Batch, it comes pre-packaged with SQL initialization scripts for most popular database platforms.\nSpring Boot can detect your database type and execute those scripts on startup.\nIf you use an embedded database, this happens by default.\nYou can also enable it for any database type, as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.batch.jdbc.initialize-schema=always\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n batch:\n jdbc:\n initialize-schema: "always"\n')])])]),a("p",[e._v("You can also switch off the initialization explicitly by setting "),a("code",[e._v("spring.batch.jdbc.initialize-schema")]),e._v(" to "),a("code",[e._v("never")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_9-5-use-a-higher-level-database-migration-tool"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-5-use-a-higher-level-database-migration-tool"}},[e._v("#")]),e._v(" 9.5. Use a Higher-level Database Migration Tool")]),e._v(" "),a("p",[e._v("Spring Boot supports two higher-level migration tools: "),a("a",{attrs:{href:"https://flywaydb.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Flyway"),a("OutboundLink")],1),e._v(" and "),a("a",{attrs:{href:"https://www.liquibase.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Liquibase"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h4",{attrs:{id:"_9-5-1-execute-flyway-database-migrations-on-startup"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-5-1-execute-flyway-database-migrations-on-startup"}},[e._v("#")]),e._v(" 9.5.1. Execute Flyway Database Migrations on Startup")]),e._v(" "),a("p",[e._v("To automatically run Flyway database migrations on startup, add the "),a("code",[e._v("org.flywaydb:flyway-core")]),e._v(" to your classpath.")]),e._v(" "),a("p",[e._v("Typically, migrations are scripts in the form "),a("code",[e._v("V__.sql")]),e._v(" (with "),a("code",[e._v("")]),e._v(" an underscore-separated version, such as ‘1’ or ‘2_1’).\nBy default, they are in a directory called "),a("code",[e._v("classpath:db/migration")]),e._v(", but you can modify that location by setting "),a("code",[e._v("spring.flyway.locations")]),e._v(".\nThis is a comma-separated list of one or more "),a("code",[e._v("classpath:")]),e._v(" or "),a("code",[e._v("filesystem:")]),e._v(" locations.\nFor example, the following configuration would search for scripts in both the default classpath location and the "),a("code",[e._v("/opt/migration")]),e._v(" directory:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.flyway.locations=classpath:db/migration,filesystem:/opt/migration\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n flyway:\n locations: "classpath:db/migration,filesystem:/opt/migration"\n')])])]),a("p",[e._v("You can also add a special "),a("code",[e._v("{vendor}")]),e._v(" placeholder to use vendor-specific scripts.\nAssume the following:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.flyway.locations=classpath:db/migration/{vendor}\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n flyway:\n locations: "classpath:db/migration/{vendor}"\n')])])]),a("p",[e._v("Rather than using "),a("code",[e._v("db/migration")]),e._v(", the preceding configuration sets the directory to use according to the type of the database (such as "),a("code",[e._v("db/migration/mysql")]),e._v(" for MySQL).\nThe list of supported databases is available in "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jdbc/DatabaseDriver.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("DatabaseDriver")]),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("p",[e._v("Migrations can also be written in Java.\nFlyway will be auto-configured with any beans that implement "),a("code",[e._v("JavaMigration")]),e._v(".")]),e._v(" "),a("p",[a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayProperties.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("FlywayProperties")]),a("OutboundLink")],1),e._v(" 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.\nIf you need more control over the configuration, consider registering a "),a("code",[e._v("FlywayConfigurationCustomizer")]),e._v(" bean.")]),e._v(" "),a("p",[e._v("Spring Boot calls "),a("code",[e._v("Flyway.migrate()")]),e._v(" to perform the database migration.\nIf you would like more control, provide a "),a("code",[e._v("@Bean")]),e._v(" that implements "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/flyway/FlywayMigrationStrategy.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("FlywayMigrationStrategy")]),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("p",[e._v("Flyway supports SQL and Java "),a("a",{attrs:{href:"https://flywaydb.org/documentation/concepts/callbacks",target:"_blank",rel:"noopener noreferrer"}},[e._v("callbacks"),a("OutboundLink")],1),e._v(".\nTo use SQL-based callbacks, place the callback scripts in the "),a("code",[e._v("classpath:db/migration")]),e._v(" directory.\nTo use Java-based callbacks, create one or more beans that implement "),a("code",[e._v("Callback")]),e._v(".\nAny such beans are automatically registered with "),a("code",[e._v("Flyway")]),e._v(".\nThey can be ordered by using "),a("code",[e._v("@Order")]),e._v(" or by implementing "),a("code",[e._v("Ordered")]),e._v(".\nBeans that implement the deprecated "),a("code",[e._v("FlywayCallback")]),e._v(" interface can also be detected, however they cannot be used alongside "),a("code",[e._v("Callback")]),e._v(" beans.")]),e._v(" "),a("p",[e._v("By default, Flyway autowires the ("),a("code",[e._v("@Primary")]),e._v(") "),a("code",[e._v("DataSource")]),e._v(" in your context and uses that for migrations.\nIf you like to use a different "),a("code",[e._v("DataSource")]),e._v(", you can create one and mark its "),a("code",[e._v("@Bean")]),e._v(" as "),a("code",[e._v("@FlywayDataSource")]),e._v(".\nIf you do so and want two data sources, remember to create another one and mark it as "),a("code",[e._v("@Primary")]),e._v(".\nAlternatively, you can use Flyway’s native "),a("code",[e._v("DataSource")]),e._v(" by setting "),a("code",[e._v("spring.flyway.[url,user,password]")]),e._v(" in external properties.\nSetting either "),a("code",[e._v("spring.flyway.url")]),e._v(" or "),a("code",[e._v("spring.flyway.user")]),e._v(" is sufficient to cause Flyway to use its own "),a("code",[e._v("DataSource")]),e._v(".\nIf any of the three properties has not been set, the value of its equivalent "),a("code",[e._v("spring.datasource")]),e._v(" property will be used.")]),e._v(" "),a("p",[e._v("You can also use Flyway to provide data for specific scenarios.\nFor example, you can place test-specific migrations in "),a("code",[e._v("src/test/resources")]),e._v(" and they are run only when your application starts for testing.\nAlso, you can use profile-specific configuration to customize "),a("code",[e._v("spring.flyway.locations")]),e._v(" so that certain migrations run only when a particular profile is active.\nFor example, in "),a("code",[e._v("application-dev.properties")]),e._v(", you might specify the following setting:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("spring.flyway.locations=classpath:/db/migration,classpath:/dev/db/migration\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('spring:\n flyway:\n locations: "classpath:/db/migration,classpath:/dev/db/migration"\n')])])]),a("p",[e._v("With that setup, migrations in "),a("code",[e._v("dev/db/migration")]),e._v(" run only when the "),a("code",[e._v("dev")]),e._v(" profile is active.")]),e._v(" "),a("h4",{attrs:{id:"_9-5-2-execute-liquibase-database-migrations-on-startup"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-5-2-execute-liquibase-database-migrations-on-startup"}},[e._v("#")]),e._v(" 9.5.2. Execute Liquibase Database Migrations on Startup")]),e._v(" "),a("p",[e._v("To automatically run Liquibase database migrations on startup, add the "),a("code",[e._v("org.liquibase:liquibase-core")]),e._v(" to your classpath.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("When you add the "),a("code",[e._v("org.liquibase:liquibase-core")]),e._v(" to your classpath, database migrations run by default for both during application startup and before your tests run."),a("br"),e._v("This behavior can be customized by using the "),a("code",[e._v("spring.liquibase.enabled")]),e._v(" property, setting different values in the "),a("code",[e._v("main")]),e._v(" and "),a("code",[e._v("test")]),e._v(" configurations."),a("br"),e._v("It is not possible to use two different ways to initialize the database (for example Liquibase for application startup, JPA for test runs).")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("By default, the master change log is read from "),a("code",[e._v("db/changelog/db.changelog-master.yaml")]),e._v(", but you can change the location by setting "),a("code",[e._v("spring.liquibase.change-log")]),e._v(".\nIn addition to YAML, Liquibase also supports JSON, XML, and SQL change log formats.")]),e._v(" "),a("p",[e._v("By default, Liquibase autowires the ("),a("code",[e._v("@Primary")]),e._v(") "),a("code",[e._v("DataSource")]),e._v(" in your context and uses that for migrations.\nIf you need to use a different "),a("code",[e._v("DataSource")]),e._v(", you can create one and mark its "),a("code",[e._v("@Bean")]),e._v(" as "),a("code",[e._v("@LiquibaseDataSource")]),e._v(".\nIf you do so and you want two data sources, remember to create another one and mark it as "),a("code",[e._v("@Primary")]),e._v(".\nAlternatively, you can use Liquibase’s native "),a("code",[e._v("DataSource")]),e._v(" by setting "),a("code",[e._v("spring.liquibase.[driver-class-name,url,user,password]")]),e._v(" in external properties.\nSetting either "),a("code",[e._v("spring.liquibase.url")]),e._v(" or "),a("code",[e._v("spring.liquibase.user")]),e._v(" is sufficient to cause Liquibase to use its own "),a("code",[e._v("DataSource")]),e._v(".\nIf any of the three properties has not been set, the value of its equivalent "),a("code",[e._v("spring.datasource")]),e._v(" property will be used.")]),e._v(" "),a("p",[e._v("See "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/liquibase/LiquibaseProperties.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("LiquibaseProperties")]),a("OutboundLink")],1),e._v(" for details about available settings such as contexts, the default schema, and others.")]),e._v(" "),a("h3",{attrs:{id:"_9-6-depend-upon-an-initialized-database"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-6-depend-upon-an-initialized-database"}},[e._v("#")]),e._v(" 9.6. Depend Upon an Initialized Database")]),e._v(" "),a("p",[e._v("Database initialization is performed while the application is starting up as part of application context refresh.\nTo allow an initialized database to be accessed during startup, beans that act as database initializers and beans that require that database to have been initialized are detected automatically.\nBeans whose initialization depends upon the database having been initialized are configured to depend upon those that initialize it.\nIf, during startup, your application tries to access the database and it has not been initialized, you can configure additional detection of beans that initialize the database and require the database to have been initialized.")]),e._v(" "),a("h4",{attrs:{id:"_9-6-1-detect-a-database-initializer"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-6-1-detect-a-database-initializer"}},[e._v("#")]),e._v(" 9.6.1. Detect a Database Initializer")]),e._v(" "),a("p",[e._v("Spring Boot will automatically detect beans of the following types that initialize an SQL database:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("DataSourceScriptDatabaseInitializer")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("EntityManagerFactory")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("Flyway")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("FlywayMigrationInitializer")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("R2dbcScriptDatabaseInitializer")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("SpringLiquibase")])])])]),e._v(" "),a("p",[e._v("If you are using a third-party starter for a database initialization library, it may provide a detector such that beans of other types are also detected automatically.\nTo have other beans be detected, register an implementation of "),a("code",[e._v("DatabaseInitializerDetector")]),e._v(" in "),a("code",[e._v("META-INF/spring-factories")]),e._v(".")]),e._v(" "),a("h4",{attrs:{id:"_9-6-2-detect-a-bean-that-depends-on-database-initialization"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_9-6-2-detect-a-bean-that-depends-on-database-initialization"}},[e._v("#")]),e._v(" 9.6.2. Detect a Bean That Depends On Database Initialization")]),e._v(" "),a("p",[e._v("Spring Boot will automatically detect beans of the following types that depends upon database initialization:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("AbstractEntityManagerFactoryBean")]),e._v(" (unless "),a("code",[e._v("spring.jpa.defer-datasource-initialization")]),e._v(" is set to "),a("code",[e._v("true")]),e._v(")")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("DSLContext")]),e._v(" (jOOQ)")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("EntityManagerFactory")]),e._v(" (unless "),a("code",[e._v("spring.jpa.defer-datasource-initialization")]),e._v(" is set to "),a("code",[e._v("true")]),e._v(")")])]),e._v(" "),a("li",[a("p",[a("code",[e._v("JdbcOperations")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("NamedParameterJdbcOperations")])])])]),e._v(" "),a("p",[e._v("If you are using a third-party starter data access library, it may provide a detector such that beans of other types are also detected automatically.\nTo have other beans be detected, register an implementation of "),a("code",[e._v("DependsOnDatabaseInitializationDetector")]),e._v(" in "),a("code",[e._v("META-INF/spring-factories")]),e._v(".\nAlternatively, annotate the bean’s class or its "),a("code",[e._v("@Bean")]),e._v(" method with "),a("code",[e._v("@DependsOnDatabaseInitialization")]),e._v(".")]),e._v(" "),a("h2",{attrs:{id:"_10-messaging"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_10-messaging"}},[e._v("#")]),e._v(" 10. Messaging")]),e._v(" "),a("p",[e._v("Spring Boot offers a number of starters to support messaging.\nThis section answers questions that arise from using messaging with Spring Boot.")]),e._v(" "),a("h3",{attrs:{id:"_10-1-disable-transacted-jms-session"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_10-1-disable-transacted-jms-session"}},[e._v("#")]),e._v(" 10.1. Disable Transacted JMS Session")]),e._v(" "),a("p",[e._v("If your JMS broker does not support transacted sessions, you have to disable the support of transactions altogether.\nIf you create your own "),a("code",[e._v("JmsListenerContainerFactory")]),e._v(", there is nothing to do, since, by default it cannot be transacted.\nIf you want to use the "),a("code",[e._v("DefaultJmsListenerContainerFactoryConfigurer")]),e._v(" to reuse Spring Boot’s default, you can disable transacted sessions, as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import javax.jms.ConnectionFactory;\n\nimport org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.jms.config.DefaultJmsListenerContainerFactory;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyJmsConfiguration {\n\n @Bean\n public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory,\n DefaultJmsListenerContainerFactoryConfigurer configurer) {\n DefaultJmsListenerContainerFactory listenerFactory = new DefaultJmsListenerContainerFactory();\n configurer.configure(listenerFactory, connectionFactory);\n listenerFactory.setTransactionManager(null);\n listenerFactory.setSessionTransacted(false);\n return listenerFactory;\n }\n\n}\n\n")])])]),a("p",[e._v("The preceding example overrides the default factory, and it should be applied to any other factory that your application defines, if any.")]),e._v(" "),a("h2",{attrs:{id:"_11-batch-applications"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_11-batch-applications"}},[e._v("#")]),e._v(" 11. Batch Applications")]),e._v(" "),a("p",[e._v("A number of questions often arise when people use Spring Batch from within a Spring Boot application.\nThis section addresses those questions.")]),e._v(" "),a("h3",{attrs:{id:"_11-1-specifying-a-batch-data-source"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_11-1-specifying-a-batch-data-source"}},[e._v("#")]),e._v(" 11.1. Specifying a Batch Data Source")]),e._v(" "),a("p",[e._v("By default, batch applications require a "),a("code",[e._v("DataSource")]),e._v(" to store job details.\nSpring Batch expects a single "),a("code",[e._v("DataSource")]),e._v(" by default.\nTo have it use a "),a("code",[e._v("DataSource")]),e._v(" other than the application’s main "),a("code",[e._v("DataSource")]),e._v(", declare a "),a("code",[e._v("DataSource")]),e._v(" bean, annotating its "),a("code",[e._v("@Bean")]),e._v(" method with "),a("code",[e._v("@BatchDataSource")]),e._v(".\nIf you do so and want two data sources, remember to mark the other one "),a("code",[e._v("@Primary")]),e._v(".\nTo take greater control, implement "),a("code",[e._v("BatchConfigurer")]),e._v(".\nSee "),a("a",{attrs:{href:"https://docs.spring.io/spring-batch/docs/4.3.5/api/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("The Javadoc of "),a("code",[e._v("@EnableBatchProcessing")]),a("OutboundLink")],1),e._v(" for more details.")]),e._v(" "),a("p",[e._v("For more info about Spring Batch, see the "),a("a",{attrs:{href:"https://spring.io/projects/spring-batch",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Batch project page"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_11-2-running-spring-batch-jobs-on-startup"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_11-2-running-spring-batch-jobs-on-startup"}},[e._v("#")]),e._v(" 11.2. Running Spring Batch Jobs on Startup")]),e._v(" "),a("p",[e._v("Spring Batch auto-configuration is enabled by adding "),a("code",[e._v("@EnableBatchProcessing")]),e._v(" to one of your "),a("code",[e._v("@Configuration")]),e._v(" classes.")]),e._v(" "),a("p",[e._v("By default, it executes "),a("strong",[e._v("all")]),e._v(" "),a("code",[e._v("Jobs")]),e._v(" in the application context on startup (see "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/JobLauncherApplicationRunner.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("JobLauncherApplicationRunner")]),a("OutboundLink")],1),e._v(" for details).\nYou can narrow down to a specific job or jobs by specifying "),a("code",[e._v("spring.batch.job.names")]),e._v(" (which takes a comma-separated list of job name patterns).")]),e._v(" "),a("p",[e._v("See "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/batch/BatchAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[e._v("BatchAutoConfiguration"),a("OutboundLink")],1),e._v(" and "),a("a",{attrs:{href:"https://docs.spring.io/spring-batch/docs/4.3.5/api/org/springframework/batch/core/configuration/annotation/EnableBatchProcessing.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("@EnableBatchProcessing"),a("OutboundLink")],1),e._v(" for more details.")]),e._v(" "),a("h3",{attrs:{id:"_11-3-running-from-the-command-line"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_11-3-running-from-the-command-line"}},[e._v("#")]),e._v(" 11.3. Running from the Command Line")]),e._v(" "),a("p",[e._v("Spring Boot converts any command line argument starting with "),a("code",[e._v("--")]),e._v(" to a property to add to the "),a("code",[e._v("Environment")]),e._v(", see "),a("RouterLink",{attrs:{to:"/en/spring-boot/features.html#features.external-config.command-line-args"}},[e._v("accessing command line properties")]),e._v(".\nThis should not be used to pass arguments to batch jobs.\nTo specify batch arguments on the command line, use the regular format (that is without "),a("code",[e._v("--")]),e._v("), as shown in the following example:")],1),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("$ java -jar myapp.jar someParameter=someValue anotherParameter=anotherValue\n")])])]),a("p",[e._v("If you specify a property of the "),a("code",[e._v("Environment")]),e._v(" on the command line, it is ignored by the job.\nConsider the following command:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("$ java -jar myapp.jar --server.port=7070 someParameter=someValue\n")])])]),a("p",[e._v("This provides only one argument to the batch job: "),a("code",[e._v("someParameter=someValue")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_11-4-storing-the-job-repository"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_11-4-storing-the-job-repository"}},[e._v("#")]),e._v(" 11.4. Storing the Job Repository")]),e._v(" "),a("p",[e._v("Spring Batch requires a data store for the "),a("code",[e._v("Job")]),e._v(" repository.\nIf you use Spring Boot, you must use an actual database.\nNote that it can be an in-memory database, see "),a("a",{attrs:{href:"https://docs.spring.io/spring-batch/docs/4.3.5/reference/html/job.html#configuringJobRepository",target:"_blank",rel:"noopener noreferrer"}},[e._v("Configuring a Job Repository"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h2",{attrs:{id:"_12-actuator"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_12-actuator"}},[e._v("#")]),e._v(" 12. Actuator")]),e._v(" "),a("p",[e._v("Spring Boot includes the Spring Boot Actuator.\nThis section answers questions that often arise from its use.")]),e._v(" "),a("h3",{attrs:{id:"_12-1-change-the-http-port-or-address-of-the-actuator-endpoints"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_12-1-change-the-http-port-or-address-of-the-actuator-endpoints"}},[e._v("#")]),e._v(" 12.1. Change the HTTP Port or Address of the Actuator Endpoints")]),e._v(" "),a("p",[e._v("In a standalone application, the Actuator HTTP port defaults to the same as the main HTTP port.\nTo make the application listen on a different port, set the external property: "),a("code",[e._v("management.server.port")]),e._v(".\nTo 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 "),a("code",[e._v("management.server.address")]),e._v(" to a valid IP address to which the server is able to bind.")]),e._v(" "),a("p",[e._v("For more detail, see the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementServerProperties.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("ManagementServerProperties")]),a("OutboundLink")],1),e._v(" source code and “"),a("RouterLink",{attrs:{to:"/en/spring-boot/actuator.html#actuator.monitoring.customizing-management-server-port"}},[e._v("actuator.html")]),e._v("” in the “Production-ready features” section.")],1),e._v(" "),a("h3",{attrs:{id:"_12-2-customize-the-whitelabel-error-page"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_12-2-customize-the-whitelabel-error-page"}},[e._v("#")]),e._v(" 12.2. Customize the ‘whitelabel’ Error Page")]),e._v(" "),a("p",[e._v("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).")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Set "),a("code",[e._v("server.error.whitelabel.enabled=false")]),e._v(" to switch the default error page off."),a("br"),e._v("Doing so restores the default of the servlet container that you are using."),a("br"),e._v("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.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Overriding the error page with your own depends on the templating technology that you use.\nFor example, if you use Thymeleaf, you can add an "),a("code",[e._v("error.html")]),e._v(" template.\nIf you use FreeMarker, you can add an "),a("code",[e._v("error.ftlh")]),e._v(" template.\nIn general, you need a "),a("code",[e._v("View")]),e._v(" that resolves with a name of "),a("code",[e._v("error")]),e._v(" or a "),a("code",[e._v("@Controller")]),e._v(" that handles the "),a("code",[e._v("/error")]),e._v(" path.\nUnless you replaced some of the default configuration, you should find a "),a("code",[e._v("BeanNameViewResolver")]),e._v(" in your "),a("code",[e._v("ApplicationContext")]),e._v(", so a "),a("code",[e._v("@Bean")]),e._v(" named "),a("code",[e._v("error")]),e._v(" would be one way of doing that.\nSee "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("ErrorMvcAutoConfiguration")]),a("OutboundLink")],1),e._v(" for more options.")]),e._v(" "),a("p",[e._v("See also the section on “"),a("RouterLink",{attrs:{to:"/en/spring-boot/web.html#web.servlet.spring-mvc.error-handling"}},[e._v("Error Handling")]),e._v("” for details of how to register handlers in the servlet container.")],1),e._v(" "),a("h3",{attrs:{id:"_12-3-sanitize-sensitive-values"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_12-3-sanitize-sensitive-values"}},[e._v("#")]),e._v(" 12.3. Sanitize Sensitive Values")]),e._v(" "),a("p",[e._v("Information returned by the "),a("code",[e._v("env")]),e._v(" and "),a("code",[e._v("configprops")]),e._v(" endpoints can be somewhat sensitive so keys matching certain patterns are sanitized by default (that is their values are replaced by "),a("code",[e._v("******")]),e._v(').\nSpring Boot uses sensible defaults for such keys: any key ending with the word "password", "secret", "key", "token", "vcap_services", "sun.java.command" is entirely sanitized.\nAdditionally, any key that holds the word '),a("code",[e._v("credentials")]),e._v(" (configured as a regular expression, that is "),a("code",[e._v(".*credentials.*")]),e._v(") as part of the key is also entirely sanitized.")]),e._v(" "),a("p",[e._v("Furthermore, Spring Boot sanitizes the sensitive portion of URI-like values for keys with one of the following endings:")]),e._v(" "),a("ul",[a("li",[a("p",[a("code",[e._v("address")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("addresses")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("uri")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("uris")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("url")])])]),e._v(" "),a("li",[a("p",[a("code",[e._v("urls")])])])]),e._v(" "),a("p",[e._v("The sensitive portion of the URI is identified using the format "),a("code",[e._v("://:@:/")]),e._v(".\nFor example, for the property "),a("code",[e._v("myclient.uri=http://user1:[[email protected]](/cdn-cgi/l/email-protection):8081")]),e._v(", the resulting sanitized value is"),a("code",[e._v("http://user1:******@localhost:8081")]),e._v(".")]),e._v(" "),a("p",[e._v("The default patterns used by the "),a("code",[e._v("env")]),e._v(" and "),a("code",[e._v("configprops")]),e._v(" endpoints can be replaced using "),a("code",[e._v("management.endpoint.env.keys-to-sanitize")]),e._v(" and "),a("code",[e._v("management.endpoint.configprops.keys-to-sanitize")]),e._v(" respectively.\nAlternatively, additional patterns can be configured using "),a("code",[e._v("management.endpoint.env.additional-keys-to-sanitize")]),e._v(" and "),a("code",[e._v("management.endpoint.configprops.additional-keys-to-sanitize")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_12-4-map-health-indicators-to-micrometer-metrics"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_12-4-map-health-indicators-to-micrometer-metrics"}},[e._v("#")]),e._v(" 12.4. Map Health Indicators to Micrometer Metrics")]),e._v(" "),a("p",[e._v("Spring Boot health indicators return a "),a("code",[e._v("Status")]),e._v(" type to indicate the overall system health.\nIf you want to monitor or alert on levels of health for a particular application, you can export these statuses as metrics with Micrometer.\nBy default, the status codes “UP”, “DOWN”, “OUT_OF_SERVICE” and “UNKNOWN” are used by Spring Boot.\nTo export these, you will need to convert these states to some set of numbers so that they can be used with a Micrometer "),a("code",[e._v("Gauge")]),e._v(".")]),e._v(" "),a("p",[e._v("The following example shows one way to write such an exporter:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import io.micrometer.core.instrument.Gauge;\nimport io.micrometer.core.instrument.MeterRegistry;\n\nimport org.springframework.boot.actuate.health.HealthEndpoint;\nimport org.springframework.boot.actuate.health.Status;\nimport org.springframework.context.annotation.Configuration;\n\n@Configuration(proxyBeanMethods = false)\npublic class MyHealthMetricsExportConfiguration {\n\n public MyHealthMetricsExportConfiguration(MeterRegistry registry, HealthEndpoint healthEndpoint) {\n // This example presumes common tags (such as the app) are applied elsewhere\n Gauge.builder("health", healthEndpoint, this::getStatusCode).strongReference(true).register(registry);\n }\n\n private int getStatusCode(HealthEndpoint health) {\n Status status = health.health().getStatus();\n if (Status.UP.equals(status)) {\n return 3;\n }\n if (Status.OUT_OF_SERVICE.equals(status)) {\n return 2;\n }\n if (Status.DOWN.equals(status)) {\n return 1;\n }\n return 0;\n }\n\n}\n\n')])])]),a("h2",{attrs:{id:"_13-security"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_13-security"}},[e._v("#")]),e._v(" 13. Security")]),e._v(" "),a("p",[e._v("This section addresses questions about security when working with Spring Boot, including questions that arise from using Spring Security with Spring Boot.")]),e._v(" "),a("p",[e._v("For more about Spring Security, see the "),a("a",{attrs:{href:"https://spring.io/projects/spring-security",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Security project page"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_13-1-switch-off-the-spring-boot-security-configuration"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_13-1-switch-off-the-spring-boot-security-configuration"}},[e._v("#")]),e._v(" 13.1. Switch off the Spring Boot Security Configuration")]),e._v(" "),a("p",[e._v("If you define a "),a("code",[e._v("@Configuration")]),e._v(" with a "),a("code",[e._v("WebSecurityConfigurerAdapter")]),e._v(" or a "),a("code",[e._v("SecurityFilterChain")]),e._v(" bean in your application, it switches off the default webapp security settings in Spring Boot.")]),e._v(" "),a("h3",{attrs:{id:"_13-2-change-the-userdetailsservice-and-add-user-accounts"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_13-2-change-the-userdetailsservice-and-add-user-accounts"}},[e._v("#")]),e._v(" 13.2. Change the UserDetailsService and Add User Accounts")]),e._v(" "),a("p",[e._v("If you provide a "),a("code",[e._v("@Bean")]),e._v(" of type "),a("code",[e._v("AuthenticationManager")]),e._v(", "),a("code",[e._v("AuthenticationProvider")]),e._v(", or "),a("code",[e._v("UserDetailsService")]),e._v(", the default "),a("code",[e._v("@Bean")]),e._v(" for "),a("code",[e._v("InMemoryUserDetailsManager")]),e._v(" is not created.\nThis means you have the full feature set of Spring Security available (such as "),a("a",{attrs:{href:"https://docs.spring.io/spring-security/reference/5.6.2/servlet/authentication/index.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("various authentication options"),a("OutboundLink")],1),e._v(").")]),e._v(" "),a("p",[e._v("The easiest way to add user accounts is to provide your own "),a("code",[e._v("UserDetailsService")]),e._v(" bean.")]),e._v(" "),a("h3",{attrs:{id:"_13-3-enable-https-when-running-behind-a-proxy-server"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_13-3-enable-https-when-running-behind-a-proxy-server"}},[e._v("#")]),e._v(" 13.3. Enable HTTPS When Running behind a Proxy Server")]),e._v(" "),a("p",[e._v("Ensuring that all your main endpoints are only available over HTTPS is an important chore for any application.\nIf you use Tomcat as a servlet container, then Spring Boot adds Tomcat’s own "),a("code",[e._v("RemoteIpValve")]),e._v(" automatically if it detects some environment settings, and you should be able to rely on the "),a("code",[e._v("HttpServletRequest")]),e._v(" to report whether it is secure or not (even downstream of a proxy server that handles the real SSL termination).\nThe standard behavior is determined by the presence or absence of certain request headers ("),a("code",[e._v("x-forwarded-for")]),e._v(" and "),a("code",[e._v("x-forwarded-proto")]),e._v("), whose names are conventional, so it should work with most front-end proxies.\nYou can switch on the valve by adding some entries to "),a("code",[e._v("application.properties")]),e._v(", as shown in the following example:")]),e._v(" "),a("p",[e._v("Properties")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("server.tomcat.remoteip.remote-ip-header=x-forwarded-for\nserver.tomcat.remoteip.protocol-header=x-forwarded-proto\n")])])]),a("p",[e._v("Yaml")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('server:\n tomcat:\n remoteip:\n remote-ip-header: "x-forwarded-for"\n protocol-header: "x-forwarded-proto"\n')])])]),a("p",[e._v("(The presence of either of those properties switches on the valve.\nAlternatively, you can add the "),a("code",[e._v("RemoteIpValve")]),e._v(" by customizing the "),a("code",[e._v("TomcatServletWebServerFactory")]),e._v(" using a "),a("code",[e._v("WebServerFactoryCustomizer")]),e._v(" bean.)")]),e._v(" "),a("p",[e._v("To configure Spring Security to require a secure channel for all (or some) requests, consider adding your own "),a("code",[e._v("SecurityFilterChain")]),e._v(" bean that adds the following "),a("code",[e._v("HttpSecurity")]),e._v(" configuration:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\nimport org.springframework.security.web.SecurityFilterChain;\n\n@Configuration\npublic class MySecurityConfig {\n\n @Bean\n public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {\n // Customize the application security ...\n http.requiresChannel().anyRequest().requiresSecure();\n return http.build();\n }\n\n}\n\n")])])]),a("h2",{attrs:{id:"_14-hot-swapping"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-hot-swapping"}},[e._v("#")]),e._v(" 14. Hot Swapping")]),e._v(" "),a("p",[e._v("Spring Boot supports hot swapping.\nThis section answers questions about how it works.")]),e._v(" "),a("h3",{attrs:{id:"_14-1-reload-static-content"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-1-reload-static-content"}},[e._v("#")]),e._v(" 14.1. Reload Static Content")]),e._v(" "),a("p",[e._v("There are several options for hot reloading.\nThe recommended approach is to use "),a("RouterLink",{attrs:{to:"/en/spring-boot/using.html#using.devtools"}},[a("code",[e._v("spring-boot-devtools")])]),e._v(', 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).\nDevtools works by monitoring the classpath for changes.\nThis means that static resource changes must be "built" for the change to take effect.\nBy default, this happens automatically in Eclipse when you save your changes.\nIn IntelliJ IDEA, the Make Project command triggers the necessary build.\nDue to the '),a("RouterLink",{attrs:{to:"/en/spring-boot/using.html#using.devtools.restart.excluding-resources"}},[e._v("default restart exclusions")]),e._v(", changes to static resources do not trigger a restart of your application.\nThey do, however, trigger a live reload.")],1),e._v(" "),a("p",[e._v("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).")]),e._v(" "),a("p",[e._v("Finally, the "),a("RouterLink",{attrs:{to:"/en/spring-boot/build-tool-plugins.html#build-tool-plugins"}},[e._v("Maven and Gradle plugins")]),e._v(" can be configured (see the "),a("code",[e._v("addResources")]),e._v(" property) to support running from the command line with reloading of static files directly from source.\nYou can use that with an external css/js compiler process if you are writing that code with higher-level tools.")],1),e._v(" "),a("h3",{attrs:{id:"_14-2-reload-templates-without-restarting-the-container"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-2-reload-templates-without-restarting-the-container"}},[e._v("#")]),e._v(" 14.2. Reload Templates without Restarting the Container")]),e._v(" "),a("p",[e._v("Most of the templating technologies supported by Spring Boot include a configuration option to disable caching (described later in this document).\nIf you use the "),a("code",[e._v("spring-boot-devtools")]),e._v(" module, these properties are "),a("RouterLink",{attrs:{to:"/en/spring-boot/using.html#using.devtools.property-defaults"}},[e._v("automatically configured")]),e._v(" for you at development time.")],1),e._v(" "),a("h4",{attrs:{id:"_14-2-1-thymeleaf-templates"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-2-1-thymeleaf-templates"}},[e._v("#")]),e._v(" 14.2.1. Thymeleaf Templates")]),e._v(" "),a("p",[e._v("If you use Thymeleaf, set "),a("code",[e._v("spring.thymeleaf.cache")]),e._v(" to "),a("code",[e._v("false")]),e._v(".\nSee "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("ThymeleafAutoConfiguration")]),a("OutboundLink")],1),e._v(" for other Thymeleaf customization options.")]),e._v(" "),a("h4",{attrs:{id:"_14-2-2-freemarker-templates"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-2-2-freemarker-templates"}},[e._v("#")]),e._v(" 14.2.2. FreeMarker Templates")]),e._v(" "),a("p",[e._v("If you use FreeMarker, set "),a("code",[e._v("spring.freemarker.cache")]),e._v(" to "),a("code",[e._v("false")]),e._v(".\nSee "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/freemarker/FreeMarkerAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("FreeMarkerAutoConfiguration")]),a("OutboundLink")],1),e._v(" for other FreeMarker customization options.")]),e._v(" "),a("h4",{attrs:{id:"_14-2-3-groovy-templates"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-2-3-groovy-templates"}},[e._v("#")]),e._v(" 14.2.3. Groovy Templates")]),e._v(" "),a("p",[e._v("If you use Groovy templates, set "),a("code",[e._v("spring.groovy.template.cache")]),e._v(" to "),a("code",[e._v("false")]),e._v(".\nSee "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/groovy/template/GroovyTemplateAutoConfiguration.java",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("GroovyTemplateAutoConfiguration")]),a("OutboundLink")],1),e._v(" for other Groovy customization options.")]),e._v(" "),a("h3",{attrs:{id:"_14-3-fast-application-restarts"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-3-fast-application-restarts"}},[e._v("#")]),e._v(" 14.3. Fast Application Restarts")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("spring-boot-devtools")]),e._v(" module includes support for automatic application restarts.\nWhile not as fast as technologies such as "),a("a",{attrs:{href:"https://www.jrebel.com/products/jrebel",target:"_blank",rel:"noopener noreferrer"}},[e._v("JRebel"),a("OutboundLink")],1),e._v(" it is usually significantly faster than a “cold start”.\nYou should probably give it a try before investigating some of the more complex reload options discussed later in this document.")]),e._v(" "),a("p",[e._v("For more details, see the "),a("RouterLink",{attrs:{to:"/en/spring-boot/using.html#using.devtools"}},[e._v("using.html")]),e._v(" section.")],1),e._v(" "),a("h3",{attrs:{id:"_14-4-reload-java-classes-without-restarting-the-container"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_14-4-reload-java-classes-without-restarting-the-container"}},[e._v("#")]),e._v(" 14.4. Reload Java Classes without Restarting the Container")]),e._v(" "),a("p",[e._v("Many modern IDEs (Eclipse, IDEA, and others) support hot swapping of bytecode.\nConsequently, if you make a change that does not affect class or method signatures, it should reload cleanly with no side effects.")]),e._v(" "),a("h2",{attrs:{id:"_15-testing"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_15-testing"}},[e._v("#")]),e._v(" 15. Testing")]),e._v(" "),a("p",[e._v("Spring Boot includes a number of testing utilities and support classes as well as a dedicated starter that provides common test dependencies.\nThis section answers common questions about testing.")]),e._v(" "),a("h3",{attrs:{id:"_15-1-testing-with-spring-security"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_15-1-testing-with-spring-security"}},[e._v("#")]),e._v(" 15.1. Testing With Spring Security")]),e._v(" "),a("p",[e._v("Spring Security provides support for running tests as a specific user.\nFor example, the test in the snippet below will run with an authenticated user that has the "),a("code",[e._v("ADMIN")]),e._v(" role.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.junit.jupiter.api.Test;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;\nimport org.springframework.security.test.context.support.WithMockUser;\nimport org.springframework.test.web.servlet.MockMvc;\n\nimport static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;\n\n@WebMvcTest(UserController.class)\nclass MySecurityTests {\n\n @Autowired\n private MockMvc mvc;\n\n @Test\n @WithMockUser(roles = "ADMIN")\n void requestProtectedUrlWithUser() throws Exception {\n this.mvc.perform(get("/"));\n }\n\n}\n\n')])])]),a("p",[e._v("Spring Security provides comprehensive integration with Spring MVC Test and this can also be used when testing controllers using the "),a("code",[e._v("@WebMvcTest")]),e._v(" slice and "),a("code",[e._v("MockMvc")]),e._v(".")]),e._v(" "),a("p",[e._v("For additional details on Spring Security’s testing support, see Spring Security’s "),a("a",{attrs:{href:"https://docs.spring.io/spring-security/reference/5.6.2/servlet/test/index.html",target:"_blank",rel:"noopener noreferrer"}},[e._v("reference documentation"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_15-2-use-testcontainers-for-integration-testing"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_15-2-use-testcontainers-for-integration-testing"}},[e._v("#")]),e._v(" 15.2. Use Testcontainers for Integration Testing")]),e._v(" "),a("p",[e._v("The "),a("a",{attrs:{href:"https://www.testcontainers.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Testcontainers"),a("OutboundLink")],1),e._v(" library provides a way to manage services running inside Docker containers.\nIt integrates with JUnit, allowing you to write a test class that can start up a container before any of the tests run.\nTestcontainers is especially useful for writing integration tests that talk to a real backend service such as MySQL, MongoDB, Cassandra and others.\nTestcontainers can be used in a Spring Boot test as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.junit.jupiter.api.Test;\nimport org.testcontainers.containers.Neo4jContainer;\nimport org.testcontainers.junit.jupiter.Container;\nimport org.testcontainers.junit.jupiter.Testcontainers;\n\nimport org.springframework.boot.test.context.SpringBootTest;\n\n@SpringBootTest\n@Testcontainers\nclass MyIntegrationTests {\n\n @Container\n static Neo4jContainer neo4j = new Neo4jContainer<>("neo4j:4.2");\n\n @Test\n void myTest() {\n // ...\n }\n\n}\n\n')])])]),a("p",[e._v("This will start up a docker container running Neo4j (if Docker is running locally) before any of the tests are run.\nIn most cases, you will need to configure the application using details from the running container, such as container IP or port.")]),e._v(" "),a("p",[e._v("This can be done with a static "),a("code",[e._v("@DynamicPropertySource")]),e._v(" method that allows adding dynamic property values to the Spring Environment.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.junit.jupiter.api.Test;\nimport org.testcontainers.containers.Neo4jContainer;\nimport org.testcontainers.junit.jupiter.Container;\nimport org.testcontainers.junit.jupiter.Testcontainers;\n\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.DynamicPropertyRegistry;\nimport org.springframework.test.context.DynamicPropertySource;\n\n@SpringBootTest\n@Testcontainers\nclass MyIntegrationTests {\n\n @Container\n static Neo4jContainer neo4j = new Neo4jContainer<>("neo4j:4.2");\n\n @Test\n void myTest() {\n // ...\n }\n\n @DynamicPropertySource\n static void neo4jProperties(DynamicPropertyRegistry registry) {\n registry.add("spring.neo4j.uri", neo4j::getBoltUrl);\n }\n\n}\n\n')])])]),a("p",[e._v("The above configuration allows Neo4j-related beans in the application to communicate with Neo4j running inside the Testcontainers-managed Docker container.")]),e._v(" "),a("h2",{attrs:{id:"_16-build"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-build"}},[e._v("#")]),e._v(" 16. Build")]),e._v(" "),a("p",[e._v("Spring Boot includes build plugins for Maven and Gradle.\nThis section answers common questions about these plugins.")]),e._v(" "),a("h3",{attrs:{id:"_16-1-generate-build-information"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-1-generate-build-information"}},[e._v("#")]),e._v(" 16.1. Generate Build Information")]),e._v(" "),a("p",[e._v("Both the Maven plugin and the Gradle plugin allow generating build information containing the coordinates, name, and version of the project.\nThe plugins can also be configured to add additional properties through configuration.\nWhen such a file is present, Spring Boot auto-configures a "),a("code",[e._v("BuildProperties")]),e._v(" bean.")]),e._v(" "),a("p",[e._v("To generate build information with Maven, add an execution for the "),a("code",[e._v("build-info")]),e._v(" goal, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n \n org.springframework.boot\n spring-boot-maven-plugin\n 2.6.4\n \n \n \n build-info\n \n \n \n \n \n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("See the "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#goals-build-info",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Boot Maven Plugin documentation"),a("OutboundLink")],1),e._v(" for more details.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The following example does the same with Gradle:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("springBoot {\n buildInfo()\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("See the "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#integrating-with-actuator-build-info",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Boot Gradle Plugin documentation"),a("OutboundLink")],1),e._v(" for more details.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_16-2-generate-git-information"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-2-generate-git-information"}},[e._v("#")]),e._v(" 16.2. Generate Git Information")]),e._v(" "),a("p",[e._v("Both Maven and Gradle allow generating a "),a("code",[e._v("git.properties")]),e._v(" file containing information about the state of your "),a("code",[e._v("git")]),e._v(" source code repository when the project was built.")]),e._v(" "),a("p",[e._v("For Maven users, the "),a("code",[e._v("spring-boot-starter-parent")]),e._v(" POM includes a pre-configured plugin to generate a "),a("code",[e._v("git.properties")]),e._v(" file.\nTo use it, add the following declaration for the "),a("a",{attrs:{href:"https://github.com/git-commit-id/git-commit-id-maven-plugin",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("Git Commit Id Plugin")]),a("OutboundLink")],1),e._v(" to your POM:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n \n pl.project13.maven\n git-commit-id-plugin\n \n \n\n")])])]),a("p",[e._v("Gradle users can achieve the same result by using the "),a("a",{attrs:{href:"https://plugins.gradle.org/plugin/com.gorylenko.gradle-git-properties",target:"_blank",rel:"noopener noreferrer"}},[a("code",[e._v("gradle-git-properties")]),a("OutboundLink")],1),e._v(" plugin, as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('plugins {\n id "com.gorylenko.gradle-git-properties" version "2.3.2"\n}\n')])])]),a("p",[e._v("Both the Maven and Gradle plugins allow the properties that are included in "),a("code",[e._v("git.properties")]),e._v(" to be configured.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("The commit time in "),a("code",[e._v("git.properties")]),e._v(" is expected to match the following format: "),a("code",[e._v("yyyy-MM-dd’T’HH:mm:ssZ")]),e._v("."),a("br"),e._v("This is the default format for both plugins listed above."),a("br"),e._v("Using this format lets the time be parsed into a "),a("code",[e._v("Date")]),e._v(" and its format, when serialized to JSON, to be controlled by Jackson’s date serialization configuration settings.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("h3",{attrs:{id:"_16-3-customize-dependency-versions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-3-customize-dependency-versions"}},[e._v("#")]),e._v(" 16.3. Customize Dependency Versions")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("spring-boot-dependencies")]),e._v(" POM manages the versions of common dependencies.\nThe Spring Boot plugins for Maven and Gradle allow these managed dependency versions to be customized using build properties.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("Each Spring Boot release is designed and tested against this specific set of third-party dependencies."),a("br"),e._v("Overriding versions may cause compatibility issues.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("To override dependency versions with Maven, see "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#using",target:"_blank",rel:"noopener noreferrer"}},[e._v("this section"),a("OutboundLink")],1),e._v(" of the Maven plugin’s documentation.")]),e._v(" "),a("p",[e._v("To override dependency versions in Gradle, see "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#managing-dependencies-dependency-management-plugin-customizing",target:"_blank",rel:"noopener noreferrer"}},[e._v("this section"),a("OutboundLink")],1),e._v(" of the Gradle plugin’s documentation.")]),e._v(" "),a("h3",{attrs:{id:"_16-4-create-an-executable-jar-with-maven"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-4-create-an-executable-jar-with-maven"}},[e._v("#")]),e._v(" 16.4. Create an Executable JAR with Maven")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("spring-boot-maven-plugin")]),e._v(" can be used to create an executable “fat” JAR.\nIf you use the "),a("code",[e._v("spring-boot-starter-parent")]),e._v(" POM, you can declare the plugin and your jars are repackaged as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n \n org.springframework.boot\n spring-boot-maven-plugin\n \n \n\n")])])]),a("p",[e._v("If you do not use the parent POM, you can still use the plugin.\nHowever, you must additionally add an "),a("code",[e._v("")]),e._v(" section, as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n \n org.springframework.boot\n spring-boot-maven-plugin\n {spring-boot-version}\n \n \n \n repackage\n \n \n \n \n \n\n")])])]),a("p",[e._v("See the "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#repackage",target:"_blank",rel:"noopener noreferrer"}},[e._v("plugin documentation"),a("OutboundLink")],1),e._v(" for full usage details.")]),e._v(" "),a("h3",{attrs:{id:"_16-5-use-a-spring-boot-application-as-a-dependency"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-5-use-a-spring-boot-application-as-a-dependency"}},[e._v("#")]),e._v(" 16.5. Use a Spring Boot Application as a Dependency")]),e._v(" "),a("p",[e._v("Like a war file, a Spring Boot application is not intended to be used as a dependency.\nIf your application contains classes that you want to share with other projects, the recommended approach is to move that code into a separate module.\nThe separate module can then be depended upon by your application and other projects.")]),e._v(" "),a("p",[e._v("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.\nThe executable archive cannot be used as a dependency as the "),a("RouterLink",{attrs:{to:"/en/spring-boot/executable-jar.html#appendix.executable-jar.nested-jars.jar-structure"}},[e._v("executable jar format")]),e._v(" packages application classes in "),a("code",[e._v("BOOT-INF/classes")]),e._v(".\nThis means that they cannot be found when the executable jar is used as a dependency.")],1),e._v(" "),a("p",[e._v("To produce the two artifacts, one that can be used as a dependency and one that is executable, a classifier must be specified.\nThis classifier is applied to the name of the executable archive, leaving the default archive for use as a dependency.")]),e._v(" "),a("p",[e._v("To configure a classifier of "),a("code",[e._v("exec")]),e._v(" in Maven, you can use the following configuration:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n \n org.springframework.boot\n spring-boot-maven-plugin\n \n exec\n \n \n \n\n")])])]),a("h3",{attrs:{id:"_16-6-extract-specific-libraries-when-an-executable-jar-runs"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-6-extract-specific-libraries-when-an-executable-jar-runs"}},[e._v("#")]),e._v(" 16.6. Extract Specific Libraries When an Executable Jar Runs")]),e._v(" "),a("p",[e._v("Most nested libraries in an executable jar do not need to be unpacked in order to run.\nHowever, certain libraries can have problems.\nFor example, JRuby includes its own nested jar support, which assumes that the "),a("code",[e._v("jruby-complete.jar")]),e._v(" is always directly available as a file in its own right.")]),e._v(" "),a("p",[e._v("To deal with any problematic libraries, you can flag that specific nested jars should be automatically unpacked when the executable jar first runs.\nSuch nested jars are written beneath the temporary directory identified by the "),a("code",[e._v("java.io.tmpdir")]),e._v(" system property.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("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.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("For example, to indicate that JRuby should be flagged for unpacking by using the Maven Plugin, you would add the following configuration:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n \n org.springframework.boot\n spring-boot-maven-plugin\n \n \n \n org.jruby\n jruby-complete\n \n \n \n \n \n\n")])])]),a("h3",{attrs:{id:"_16-7-create-a-non-executable-jar-with-exclusions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-7-create-a-non-executable-jar-with-exclusions"}},[e._v("#")]),e._v(" 16.7. Create a Non-executable JAR with Exclusions")]),e._v(" "),a("p",[e._v("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.\nFor example, the "),a("code",[e._v("application.yml")]),e._v(" configuration file might be excluded from the non-executable JAR.")]),e._v(" "),a("p",[e._v("In Maven, the executable jar must be the main artifact and you can add a classified jar for the library, as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \n \n org.springframework.boot\n spring-boot-maven-plugin\n \n \n maven-jar-plugin\n \n \n lib\n package\n \n jar\n \n \n lib\n \n application.yml\n \n \n \n \n \n \n\n")])])]),a("h3",{attrs:{id:"_16-8-remote-debug-a-spring-boot-application-started-with-maven"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-8-remote-debug-a-spring-boot-application-started-with-maven"}},[e._v("#")]),e._v(" 16.8. Remote Debug a Spring Boot Application Started with Maven")]),e._v(" "),a("p",[e._v("To attach a remote debugger to a Spring Boot application that was started with Maven, you can use the "),a("code",[e._v("jvmArguments")]),e._v(" property of the "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/",target:"_blank",rel:"noopener noreferrer"}},[e._v("maven plugin"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("p",[e._v("See "),a("a",{attrs:{href:"https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#run-example-debug",target:"_blank",rel:"noopener noreferrer"}},[e._v("this example"),a("OutboundLink")],1),e._v(" for more details.")]),e._v(" "),a("h3",{attrs:{id:"_16-9-build-an-executable-archive-from-ant-without-using-spring-boot-antlib"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_16-9-build-an-executable-archive-from-ant-without-using-spring-boot-antlib"}},[e._v("#")]),e._v(" 16.9. Build an Executable Archive from Ant without Using spring-boot-antlib")]),e._v(" "),a("p",[e._v("To build with Ant, you need to grab dependencies, compile, and then create a jar or war archive.\nTo make it executable, you can either use the "),a("code",[e._v("spring-boot-antlib")]),e._v(" module or you can follow these instructions:")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("If you are building a jar, package the application’s classes and resources in a nested "),a("code",[e._v("BOOT-INF/classes")]),e._v(" directory.\nIf you are building a war, package the application’s classes in a nested "),a("code",[e._v("WEB-INF/classes")]),e._v(" directory as usual.")])]),e._v(" "),a("li",[a("p",[e._v("Add the runtime dependencies in a nested "),a("code",[e._v("BOOT-INF/lib")]),e._v(" directory for a jar or "),a("code",[e._v("WEB-INF/lib")]),e._v(" for a war.\nRemember "),a("strong",[e._v("not")]),e._v(" to compress the entries in the archive.")])]),e._v(" "),a("li",[a("p",[e._v("Add the "),a("code",[e._v("provided")]),e._v(" (embedded container) dependencies in a nested "),a("code",[e._v("BOOT-INF/lib")]),e._v(" directory for a jar or "),a("code",[e._v("WEB-INF/lib-provided")]),e._v(" for a war.\nRemember "),a("strong",[e._v("not")]),e._v(" to compress the entries in the archive.")])]),e._v(" "),a("li",[a("p",[e._v("Add the "),a("code",[e._v("spring-boot-loader")]),e._v(" classes at the root of the archive (so that the "),a("code",[e._v("Main-Class")]),e._v(" is available).")])]),e._v(" "),a("li",[a("p",[e._v("Use the appropriate launcher (such as "),a("code",[e._v("JarLauncher")]),e._v(" for a jar file) as a "),a("code",[e._v("Main-Class")]),e._v(" attribute in the manifest and specify the other properties it needs as manifest entries — principally, by setting a "),a("code",[e._v("Start-Class")]),e._v(" property.")])])]),e._v(" "),a("p",[e._v("The following example shows how to build an executable archive with Ant:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n\n')])])]),a("h2",{attrs:{id:"_17-traditional-deployment"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_17-traditional-deployment"}},[e._v("#")]),e._v(" 17. Traditional Deployment")]),e._v(" "),a("p",[e._v("Spring Boot supports traditional deployment as well as more modern forms of deployment.\nThis section answers common questions about traditional deployment.")]),e._v(" "),a("h3",{attrs:{id:"_17-1-create-a-deployable-war-file"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_17-1-create-a-deployable-war-file"}},[e._v("#")]),e._v(" 17.1. Create a Deployable War File")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("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.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("The first step in producing a deployable war file is to provide a "),a("code",[e._v("SpringBootServletInitializer")]),e._v(" subclass and override its "),a("code",[e._v("configure")]),e._v(" method.\nDoing 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.\nTypically, you should update your application’s main class to extend "),a("code",[e._v("SpringBootServletInitializer")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.builder.SpringApplicationBuilder;\nimport org.springframework.boot.web.servlet.support.SpringBootServletInitializer;\n\n@SpringBootApplication\npublic class MyApplication extends SpringBootServletInitializer {\n\n @Override\n protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {\n return application.sources(MyApplication.class);\n }\n\n public static void main(String[] args) {\n SpringApplication.run(MyApplication.class, args);\n }\n\n}\n\n")])])]),a("p",[e._v("The next step is to update your build configuration such that your project produces a war file rather than a jar file.\nIf you use Maven and "),a("code",[e._v("spring-boot-starter-parent")]),e._v(" (which configures Maven’s war plugin for you), all you need to do is to modify "),a("code",[e._v("pom.xml")]),e._v(" to change the packaging to war, as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("war\n")])])]),a("p",[e._v("If you use Gradle, you need to modify "),a("code",[e._v("build.gradle")]),e._v(" to apply the war plugin to the project, as follows:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("apply plugin: 'war'\n")])])]),a("p",[e._v("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.\nTo do so, you need to mark the embedded servlet container dependency as being provided.")]),e._v(" "),a("p",[e._v("If you use Maven, the following example marks the servlet container (Tomcat, in this case) as being provided:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n \x3c!-- ... --\x3e\n \n org.springframework.boot\n spring-boot-starter-tomcat\n provided\n \n \x3c!-- ... --\x3e\n\n")])])]),a("p",[e._v("If you use Gradle, the following example marks the servlet container (Tomcat, in this case) as being provided:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("dependencies {\n // ...\n providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'\n // ...\n}\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[a("code",[e._v("providedRuntime")]),e._v(" is preferred to Gradle’s "),a("code",[e._v("compileOnly")]),e._v(" configuration."),a("br"),e._v("Among other limitations, "),a("code",[e._v("compileOnly")]),e._v(" dependencies are not on the test classpath, so any web-based integration tests fail.")])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("If you use the "),a("RouterLink",{attrs:{to:"/en/spring-boot/build-tool-plugins.html#build-tool-plugins"}},[e._v("Spring Boot build tools")]),e._v(", marking the embedded servlet container dependency as provided produces an executable war file with the provided dependencies packaged in a "),a("code",[e._v("lib-provided")]),e._v(" directory.\nThis means that, in addition to being deployable to a servlet container, you can also run your application by using "),a("code",[e._v("java -jar")]),e._v(" on the command line.")],1),e._v(" "),a("h3",{attrs:{id:"_17-2-convert-an-existing-application-to-spring-boot"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_17-2-convert-an-existing-application-to-spring-boot"}},[e._v("#")]),e._v(" 17.2. Convert an Existing Application to Spring Boot")]),e._v(" "),a("p",[e._v("To convert an existing non-web Spring application to a Spring Boot application, replace the code that creates your "),a("code",[e._v("ApplicationContext")]),e._v(" and replace it with calls to "),a("code",[e._v("SpringApplication")]),e._v(" or "),a("code",[e._v("SpringApplicationBuilder")]),e._v(".\nSpring MVC web applications are generally amenable to first creating a deployable war application and then migrating it later to an executable war or jar.\nSee the "),a("a",{attrs:{href:"https://spring.io/guides/gs/convert-jar-to-war/",target:"_blank",rel:"noopener noreferrer"}},[e._v("Getting Started Guide on Converting a jar to a war"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("p",[e._v("To create a deployable war by extending "),a("code",[e._v("SpringBootServletInitializer")]),e._v(" (for example, in a class called "),a("code",[e._v("Application")]),e._v(") and adding the Spring Boot "),a("code",[e._v("@SpringBootApplication")]),e._v(" annotation, use code similar to that shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.builder.SpringApplicationBuilder;\nimport org.springframework.boot.web.servlet.support.SpringBootServletInitializer;\n\n@SpringBootApplication\npublic class MyApplication extends SpringBootServletInitializer {\n\n @Override\n protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {\n // Customize the application or call application.sources(...) to add sources\n // Since our example is itself a @Configuration class (via @SpringBootApplication)\n // we actually do not need to override this method.\n return application;\n }\n\n}\n\n")])])]),a("p",[e._v("Remember that, whatever you put in the "),a("code",[e._v("sources")]),e._v(" is merely a Spring "),a("code",[e._v("ApplicationContext")]),e._v(".\nNormally, anything that already works should work here.\nThere 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.")]),e._v(" "),a("p",[e._v("Static resources can be moved to "),a("code",[e._v("/public")]),e._v(" (or "),a("code",[e._v("/static")]),e._v(" or "),a("code",[e._v("/resources")]),e._v(" or "),a("code",[e._v("/META-INF/resources")]),e._v(") in the classpath root.\nThe same applies to "),a("code",[e._v("messages.properties")]),e._v(" (which Spring Boot automatically detects in the root of the classpath).")]),e._v(" "),a("p",[e._v("Vanilla usage of Spring "),a("code",[e._v("DispatcherServlet")]),e._v(" and Spring Security should require no further changes.\nIf you have other features in your application (for instance, using other servlets or filters), you may need to add some configuration to your "),a("code",[e._v("Application")]),e._v(" context, by replacing those elements from the "),a("code",[e._v("web.xml")]),e._v(", as follows:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("A "),a("code",[e._v("@Bean")]),e._v(" of type "),a("code",[e._v("Servlet")]),e._v(" or "),a("code",[e._v("ServletRegistrationBean")]),e._v(" installs that bean in the container as if it were a "),a("code",[e._v("")]),e._v(" and "),a("code",[e._v("")]),e._v(" in "),a("code",[e._v("web.xml")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("A "),a("code",[e._v("@Bean")]),e._v(" of type "),a("code",[e._v("Filter")]),e._v(" or "),a("code",[e._v("FilterRegistrationBean")]),e._v(" behaves similarly (as a "),a("code",[e._v("")]),e._v(" and "),a("code",[e._v("")]),e._v(").")])]),e._v(" "),a("li",[a("p",[e._v("An "),a("code",[e._v("ApplicationContext")]),e._v(" in an XML file can be added through an "),a("code",[e._v("@ImportResource")]),e._v(" in your "),a("code",[e._v("Application")]),e._v(".\nAlternatively, cases where annotation configuration is heavily used already can be recreated in a few lines as "),a("code",[e._v("@Bean")]),e._v(" definitions.")])])]),e._v(" "),a("p",[e._v("Once the war file is working, you can make it executable by adding a "),a("code",[e._v("main")]),e._v(" method to your "),a("code",[e._v("Application")]),e._v(", as shown in the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public static void main(String[] args) {\n SpringApplication.run(MyApplication.class, args);\n}\n\n")])])]),a("table",[a("thead",[a("tr",[a("th"),e._v(" "),a("th",[e._v("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 "),a("code",[e._v("SpringBootServletInitializer")]),e._v(" callback and in the "),a("code",[e._v("main")]),e._v(" method in a class similar to the following:"),a("br"),a("br"),a("code",[e._v("
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return customizerBuilder(builder);
}

public static void main(String[] args) {
customizerBuilder(new SpringApplicationBuilder()).run(args);
}

private static SpringApplicationBuilder customizerBuilder(SpringApplicationBuilder builder) {
return builder.sources(MyApplication.class).bannerMode(Banner.Mode.OFF);
}

}

")])])])]),e._v(" "),a("tbody")]),e._v(" "),a("p",[e._v("Applications can fall into more than one category:")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("Servlet 3.0+ applications with no "),a("code",[e._v("web.xml")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("Applications with a "),a("code",[e._v("web.xml")]),e._v(".")])]),e._v(" "),a("li",[a("p",[e._v("Applications with a context hierarchy.")])]),e._v(" "),a("li",[a("p",[e._v("Applications without a context hierarchy.")])])]),e._v(" "),a("p",[e._v("All of these should be amenable to translation, but each might require slightly different techniques.")]),e._v(" "),a("p",[e._v("Servlet 3.0+ applications might translate pretty easily if they already use the Spring Servlet 3.0+ initializer support classes.\nNormally, all the code from an existing "),a("code",[e._v("WebApplicationInitializer")]),e._v(" can be moved into a "),a("code",[e._v("SpringBootServletInitializer")]),e._v(".\nIf your existing application has more than one "),a("code",[e._v("ApplicationContext")]),e._v(" (for example, if it uses "),a("code",[e._v("AbstractDispatcherServletInitializer")]),e._v(") then you might be able to combine all your context sources into a single "),a("code",[e._v("SpringApplication")]),e._v(".\nThe main complication you might encounter is if combining does not work and you need to maintain the context hierarchy.\nSee the "),a("a",{attrs:{href:"#howto.application.context-hierarchy"}},[e._v("entry on building a hierarchy")]),e._v(" for examples.\nAn existing parent context that contains web-specific features usually needs to be broken up so that all the "),a("code",[e._v("ServletContextAware")]),e._v(" components are in the child context.")]),e._v(" "),a("p",[e._v("Applications that are not already Spring applications might be convertible to Spring Boot applications, and the previously mentioned guidance may help.\nHowever, you may yet encounter problems.\nIn that case, we suggest "),a("a",{attrs:{href:"https://stackoverflow.com/questions/tagged/spring-boot",target:"_blank",rel:"noopener noreferrer"}},[e._v("asking questions on Stack Overflow with a tag of "),a("code",[e._v("spring-boot")]),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"_17-3-deploying-a-war-to-weblogic"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#_17-3-deploying-a-war-to-weblogic"}},[e._v("#")]),e._v(" 17.3. Deploying a WAR to WebLogic")]),e._v(" "),a("p",[e._v("To deploy a Spring Boot application to WebLogic, you must ensure that your servlet initializer "),a("strong",[e._v("directly")]),e._v(" implements "),a("code",[e._v("WebApplicationInitializer")]),e._v(" (even if you extend from a base class that already implements it).")]),e._v(" "),a("p",[e._v("A typical initializer for WebLogic should resemble the following example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("import org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.boot.web.servlet.support.SpringBootServletInitializer;\nimport org.springframework.web.WebApplicationInitializer;\n\n@SpringBootApplication\npublic class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {\n\n}\n\n")])])]),a("p",[e._v("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.\nYou can do so by adding a "),a("code",[e._v("WEB-INF/weblogic.xml")]),e._v(" file with the following contents:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('\n\n \n \n org.slf4j\n \n \n\n')])])])])}),[],!1,null,null,null);t.default=r.exports}}]);