### Start Spring Boot init.d service on Debian Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Start the installed service using the service command on Debian-based systems. If startup fails, check /var/log/.log for errors. ```bash $ service myapp start ``` -------------------------------- ### myapp.conf configuration file example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example .conf file for customizing script settings. It sets JAVA_OPTS and LOG_FOLDER. The file should be named the same as the jar but with .conf suffix and placed next to the jar file. ```plaintext JAVA_OPTS=-Xmx1024M LOG_FOLDER=/custom/log/folder ``` -------------------------------- ### Enable systemd service to start on boot Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Run this command to flag the application to start automatically on system boot. Refer to man systemctl for more details. ```bash $ systemctl enable myapp.service ``` -------------------------------- ### Boxfuse deployment output example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example output from `boxfuse run` showing the steps of fusing an image, creating AWS resources, and deploying. The output includes timings, resource IDs, and the final URL. This is the expected output when the command succeeds. ```text Fusing Image for myapp-1.0.jar ... Image fused in 00:06.838s (53937 K) -> axelfontaine/myapp:1.0 Creating axelfontaine/myapp ... Pushing axelfontaine/myapp:1.0 ... Verifying axelfontaine/myapp:1.0 ... Creating Elastic IP ... Mapping myapp-axelfontaine.boxfuse.io to 52.28.233.167 ... Waiting for AWS to create an AMI for axelfontaine/myapp:1.0 in eu-central-1 (this may take up to 50 seconds) ... AMI created in 00:23.557s -> ami-d23f38cf Creating security group boxfuse-sg_axelfontaine/myapp:1.0 ... Launching t2.micro instance of axelfontaine/myapp:1.0 (ami-d23f38cf) in eu-central-1 ... Instance launched in 00:30.306s -> i-92ef9f53 Waiting for AWS to boot Instance i-92ef9f53 and Payload to start at https://52.28.235.61/ ... Payload started in 00:29.266s -> https://52.28.235.61/ Remapping Elastic IP 52.28.233.167 to i-92ef9f53 ... Waiting 15s for AWS to complete Elastic IP Zero Downtime transition ... Deployment completed successfully. axelfontaine/myapp:1.0 is up and running at https://myapp-axelfontaine.boxfuse.io/ ``` -------------------------------- ### Start Ant with -lib option Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Command to start Ant with the -lib option pointing to the folder containing the spring-boot-antlib jar. Required for the Antlib to be available. ```shell $ ant -lib ``` -------------------------------- ### Install Spring Boot CLI with Scoop Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Install the Spring Boot CLI on Windows using Scoop. The `spring` command is installed to `~/scoop/apps/springboot/current/bin`. ```powershell > scoop bucket add extras > scoop install springboot ``` -------------------------------- ### spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Installs a CLI extension using artifact coordinates in the format group:artifact:version. All dependencies of the artifact are also installed. ```bash $ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE ``` -------------------------------- ### Create init.d symlink for Spring Boot application Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Symlink the executable jar to /etc/init.d to enable standard start, stop, restart, and status commands. The application is assumed to be installed in /var/myapp. ```bash $ sudo ln -s /var/myapp/myapp.jar /etc/init.d/myapp ``` -------------------------------- ### application.properties example for server.port and server.address Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows how to set the server.port and server.address properties in application.properties. These properties are part of the server group. ```properties server.port=9090 server.address=127.0.0.1 ``` -------------------------------- ### Equivalent application.properties for YAML example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle The application.properties equivalent of the preceding YAML example. Shows the flattened, period-separated keys. ```properties spring.application.name=cruncher spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost/test server.port=9000 ``` -------------------------------- ### Install Spring Boot CLI with SDKMAN! Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use SDKMAN! to install the Spring Boot CLI and verify the version. The output shows Spring Boot v2.2.7.RELEASE. ```bash $ sdk install springboot $ spring --version Spring Boot v2.2.7.RELEASE ``` -------------------------------- ### Startup Failure Message for Port 8080 in Use Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of a failure message produced by FailureAnalyzers when the embedded servlet container fails to start because port 8080 is already in use. The message includes a description and an action to resolve the issue. ```text *************************** APPLICATION FAILED TO START *************************** Description: Embedded servlet container failed to start. Port 8080 was already in use. Action: Identify and stop the process that's listening on port 8080 or configure this application to listen on another port. ``` -------------------------------- ### Configuration properties class with Javadoc Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of a @ConfigurationProperties class with Javadoc on each field. Use a unique namespace (e.g., 'acme') and document keys with field Javadoc. For boolean types, start descriptions with 'Whether' or 'Enable'. ```java @ConfigurationProperties("acme") public class AcmeProperties { /** * Whether to check the location of acme resources. */ private boolean checkLocation = true; /** * Timeout for establishing a connection to the acme server. */ private Duration loginTimeout = Duration.ofSeconds(3); // getters & setters } ``` -------------------------------- ### Install dev instance of Spring Boot CLI with SDKMAN! Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Install a local 'dev' instance pointing to your built Spring Boot CLI. The output shows Spring CLI v2.2.7.RELEASE. ```bash $ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.2.7.RELEASE-bin/spring-2.2.7.RELEASE/ $ sdk default springboot dev $ spring --version Spring CLI v2.2.7.RELEASE ``` -------------------------------- ### Install Spring Boot CLI with Homebrew Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Install the Spring Boot CLI on macOS using Homebrew. The `spring` command is installed to `/usr/local/bin`. ```bash $ brew tap pivotal/tap $ brew install springboot ``` -------------------------------- ### List installed Spring Boot CLI versions with SDKMAN! Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows the output of `sdk ls springboot`, listing the local 'dev' instance and the installed 2.2.7.RELEASE version. ```bash $ sdk ls springboot ================================================================================ Available Springboot Versions ================================================================================ > + dev * 2.2.7.RELEASE ================================================================================ + - local version * - installed > - currently in use ================================================================================ ``` -------------------------------- ### Configure auto-start for init.d service on Debian Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use update-rc.d to flag the application to start automatically. Replace with the desired startup priority. ```bash $ update-rc.d myapp defaults ``` -------------------------------- ### Console log color conversion example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows how to specify a color for a log conversion pattern using the %clr conversion word. The example makes the timestamp yellow. ```plaintext %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} ``` -------------------------------- ### Application.java with @SpringBootApplication Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example main application class using @SpringBootApplication and SpringApplication.run. ```java package com.example.myapplication; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` -------------------------------- ### Any provider example for system.state Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle JSON metadata snippet showing the 'any' provider for the 'system.state' property, offering 'on' and 'off' as auto-completion values while allowing any other value. ```json {"hints": [ { "name": "system.state", "values": [ { "value": "on" }, { "value": "off" } ], "providers": [ { "name": "any" } ] } ]} ``` -------------------------------- ### Logging pattern with MDC example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of a log line format when using logging.pattern.level=user:%X{user} %5p. Shows the default log format with an MDC entry for 'user'. ```text 2019-08-30 12:30:04.031 user:someone INFO 22174 --- [ nio-8080-exec-0] demo.Controller Handling authenticated request ``` -------------------------------- ### Install Spring Boot CLI with MacPorts Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Install the Spring Boot CLI on macOS using MacPorts. ```bash $ sudo port install spring-boot-cli ``` -------------------------------- ### Run the executable jar with java -jar Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Starts the application from the packaged jar. The output shows the Spring Boot banner and a startup log line with the application name and startup time. ```bash $ java -jar target/myproject-0.0.1-SNAPSHOT.jar . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.2.7.RELEASE) ....... . . . ....... . . . (log output here) ....... . . . ........ Started Example in 2.536 seconds (JVM running for 2.864) ``` -------------------------------- ### Project structure for trigger file Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example directory structure showing where the trigger file .reloadtrigger should be placed on the classpath. ```text src +- main +- resources +- .reloadtrigger ``` -------------------------------- ### Repackage Implementation Example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows a typical repackage implementation using Repackager and Libraries. It sets backupSource to false and provides a Libraries implementation with a doWithLibraries method for build-system-specific dependency handling. ```java Repackager repackager = new Repackager(sourceJarFile); repackager.setBackupSource(false); repackager.repackage(new Libraries() { @Override public void doWithLibraries(LibraryCallback callback) throws IOException { // Build system specific implementation, callback for each dependency // callback.library(new Library(nestedFile, LibraryScope.COMPILE)); } }); ``` -------------------------------- ### Check Java Version Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Run this command to verify your Java installation before installing Spring Boot. Requires Java SDK v1.8 or higher. ```bash $ java -version ``` -------------------------------- ### YAML external properties example (application.yml) Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example YAML file for external properties. Create application.yml in the classpath root and add snakeyaml dependency (org.yaml:snakeyaml, included with spring-boot-starter). YAML is parsed to a Map and flattened to period-separated keys. ```yaml spring: application: name: cruncher datasource: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost/test server: port: 9000 ``` -------------------------------- ### Spring Boot configuration metadata JSON example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows the JSON structure of META-INF/spring-configuration-metadata.json with groups, properties, and hints. The example includes server and spring.jpa.hibernate groups, properties like server.port and spring.jpa.hibernate.ddl-auto, and hints for ddl-auto values. ```json {"groups": [ { "name": "server", "type": "org.springframework.boot.autoconfigure.web.ServerProperties", "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" }, { "name": "spring.jpa.hibernate", "type": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate", "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties", "sourceMethod": "getHibernate()" } ... ],"properties": [ { "name": "server.port", "type": "java.lang.Integer", "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" }, { "name": "server.address", "type": "java.net.InetAddress", "sourceType": "org.springframework.boot.autoconfigure.web.ServerProperties" }, { "name": "spring.jpa.hibernate.ddl-auto", "type": "java.lang.String", "description": "DDL mode. This is actually a shortcut for the \"hibernate.hbm2ddl.auto\" property.", "sourceType": "org.springframework.boot.autoconfigure.orm.jpa.JpaProperties$Hibernate" } ... ],"hints": [ { "name": "spring.jpa.hibernate.ddl-auto", "values": [ { "value": "none", "description": "Disable DDL handling." }, { "value": "validate", "description": "Validate the schema, make no changes to the database." }, { "value": "update", "description": "Update the schema if necessary." }, { "value": "create", "description": "Create the schema and destroy previous data." }, { "value": "create-drop", "description": "Create and then destroy the schema at the end of the session." } ] } ]} ``` -------------------------------- ### Info endpoint response with custom example entry Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Expected JSON response from the info endpoint after adding the custom InfoContributor. It shows the additional 'example' entry with the key-value pair. ```json { "example": { "key" : "value" } } ``` -------------------------------- ### Example test with @Autowired MBeanServer Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows a test class with an autowired MBeanServer field and a test method. The code is incomplete as it ends with a closing brace without a class declaration, but it is displayed as an example in the testing section. ```java @Autowired private MBeanServer mBeanServer; @Test void exampleTest() { // ... } } ``` -------------------------------- ### Example @ConfigurationProperties class with nested class Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Java class showing how inner classes are automatically considered nested properties. The example produces metadata for server.name, server.host.ip, and server.host.port. ```java @ConfigurationProperties(prefix="server") public class ServerProperties { private String name; private Host host; // ... getter and setters public static class Host { private String ip; private int port; // ... getter and setters } } ``` -------------------------------- ### Remote Client Application Startup Output Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example output when running the remote client application (RemoteSpringApplication). It shows the Spring Boot Remote banner and version 2.2.7.RELEASE. ```text . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ ___ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | | _ \___ _ __ ___| |_ ___ \ \ \ \ \\/ ___)| |_)| | | | | || (_| []::::::[] / -_) ' \/ _ \ _/ -_) ) ) ) ) ' |____| .__|_| |_|_| |_\__, | |_|_\___|_|_|_\___/\__\___|/ / / / =========|_|==============|___/===================================/_/_/_/ :: Spring Boot Remote :: 2.2.7.RELEASE ``` -------------------------------- ### Spring Boot startup banner output Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle This is the typical console output when a Spring Boot application starts, showing the Spring Boot banner and version. It is useful for verifying that the application is starting correctly. ```text . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: v2.2.7.RELEASE ``` -------------------------------- ### Expand info properties at build time with Maven Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Rewrites the previous example to expand info properties at build time using Maven placeholders. Assumes Maven is used. ```properties info.app.encoding=@project.build.sourceEncoding@ info.app.java.source=@java.version@ info.app.java.target=@java.version@ ``` -------------------------------- ### Enable Spring Boot CLI command-line completion Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Source the completion script for bash or zsh. The example shows the available commands after pressing TAB. ```bash $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring $ spring grab help jar run test version ``` -------------------------------- ### Class-reference provider example for server.servlet.jsp.class-name Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle JSON metadata snippet showing the 'class-reference' provider for the 'server.servlet.jsp.class-name' property, with a target parameter of 'javax.servlet.http.HttpServlet'. ```json {"hints": [ { "name": "server.servlet.jsp.class-name", "providers": [ { "name": "class-reference", "parameters": { "target": "javax.servlet.http.HttpServlet" } } ] } ]} ``` -------------------------------- ### Run a Groovy script with spring run Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Compiles and runs a Groovy script using the `run` command. The example runs `hello.groovy`. ```bash $ spring run hello.groovy ``` -------------------------------- ### spring init --dependencies=web,data-jpa my-project Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Creates a new project using start.spring.io. The example creates a Maven-based project with spring-boot-starter-web and spring-boot-starter-data-jpa in a my-project directory. Output shows the service URL and extraction path. ```bash $ spring init --dependencies=web,data-jpa my-project Using service at https://start.spring.io Project extracted to '/Users/developer/example/my-project' ``` -------------------------------- ### Configure common tags with management.metrics.tags Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Add common tags to all meters. The example adds 'region' and 'stack' tags with values 'us-east-1' and 'prod'. ```properties management.metrics.tags.region=us-east-1 management.metrics.tags.stack=prod ``` -------------------------------- ### WebLogic servlet initializer implementing WebApplicationInitializer Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle For WebLogic deployment, the servlet initializer must directly implement WebApplicationInitializer. This example shows a typical initializer that extends SpringBootServletInitializer and implements WebApplicationInitializer. ```java import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.web.WebApplicationInitializer; @SpringBootApplication public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer { ``` -------------------------------- ### Create Example.java with Spring Boot annotations Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Create this Java file at src/main/java/Example.java to define a simple web controller. The @RestController and @RequestMapping annotations handle web requests, while @EnableAutoConfiguration configures Spring based on dependencies. The main method delegates to SpringApplication.run to bootstrap the application. ```java import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.web.bind.annotation.*; @RestController @EnableAutoConfiguration public class Example { @RequestMapping("/") String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(Example.class, args); } } ``` -------------------------------- ### Injecting RSocketRequester.Builder in a service Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of injecting RSocketRequester.Builder as a prototype bean and connecting to a TCP server. The builder is stateful, so each injection point gets a new instance. ```java @Service public class MyService { private final Mono rsocketRequester; public MyService(RSocketRequester.Builder rsocketRequesterBuilder) { this.rsocketRequester = rsocketRequesterBuilder .connectTcp("example.org", 9898).cache(); } public Mono someRSocketCall(String name) { return this.rsocketRequester.flatMap(req -> req.route("user").data(name).retrieveMono(User.class)); } } ``` -------------------------------- ### Customize application with runApplication and setBannerMode(OFF) Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Customize the application by passing a configuration block to runApplication. This example sets the banner mode to OFF. ```kotlin runApplication(*args) { setBannerMode(OFF) } ``` -------------------------------- ### MockMvc test with @WebMvcTest Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use @WebMvcTest to test a single controller with MockMvc, mocking collaborators with @MockBean. The example verifies a GET request returns expected text. ```java import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.autoconfigure.web.servlet.*; import org.springframework.boot.test.mock.mockito.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @WebMvcTest(UserVehicleController.class) class MyControllerTests { @Autowired private MockMvc mvc; @MockBean private UserVehicleService userVehicleService; @Test void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); } } ``` -------------------------------- ### Externalize SpringApplication configuration with spring.main.* Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example application.properties settings that disable the web application type and banner mode, preventing the banner from printing and the embedded web server from starting. ```properties spring.main.web-application-type=none spring.main.banner-mode=off ``` -------------------------------- ### Pass command-line arguments to the application with -- Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use `--` to separate application arguments from Spring CLI arguments. The example sets `--server.port=9000`. ```bash $ spring run hello.groovy -- --server.port=9000 ``` -------------------------------- ### WebTestClient test with @AutoConfigureWebTestClient Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use @SpringBootTest with @AutoConfigureWebTestClient to inject a WebTestClient for testing reactive web applications. The example performs a GET request to '/' and expects status 200 and body 'Hello World'. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.reactive.server.WebTestClient; @SpringBootTest @AutoConfigureWebTestClient class MockWebTestClientExampleTests { @Test void exampleTest(@Autowired WebTestClient webClient) { webClient.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello World"); } } ``` -------------------------------- ### spring init --list Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Lists the capabilities of the start.spring.io service, including available dependencies and project types. The output shows a partial list with the default project type maven-project. ```bash $ spring init --list ======================================= Capabilities of https://start.spring.io ======================================= Available dependencies: ----------------------- actuator - Actuator: Production ready features to help you monitor and manage your application ... web - Web: Support for full-stack web development, including Tomcat and spring-webmvc websocket - Websocket: Support for WebSocket development ws - WS: Support for Spring Web Services Available project types: ------------------------ gradle-build - Gradle Config [format:build, build:gradle] gradle-project - Gradle Project [format:project, build:gradle] maven-build - Maven POM [format:build, build:maven] maven-project - Maven Project [format:project, build:maven] (default) ... ``` -------------------------------- ### Customize Tomcat WebServerFactory with WebServerFactoryCustomizer Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of a WebServerFactoryCustomizer component for Tomcat with the Servlet stack. Use this to customize the server factory when configuration keys are insufficient. ```java @Component public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer { @Override public void customize(TomcatServletWebServerFactory factory) { // customize the factory here } } ``` -------------------------------- ### Enable CORS for actuator endpoints Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Allows GET and POST calls from example.com by setting management.endpoints.web.cors.allowed-origins and allowed-methods. CORS is disabled by default until these properties are set. ```properties management.endpoints.web.cors.allowed-origins=https://example.com management.endpoints.web.cors.allowed-methods=GET,POST ``` -------------------------------- ### spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Creates a Gradle project using Java 8 and war packaging with the websocket dependency. The output shows the service URL and that the content was saved to sample-app.zip. ```bash $ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip Using service at https://start.spring.io Content saved to 'sample-app.zip' ``` -------------------------------- ### TestRestTemplate test with RANDOM_PORT Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) with TestRestTemplate to make REST calls to a running server without spring-webflux. The example performs a GET request and asserts the response body equals 'Hello World'. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class RandomPortTestRestTemplateExampleTests { @Test void exampleTest(@Autowired TestRestTemplate restTemplate) { String body = restTemplate.getForObject("/", String.class); assertThat(body).isEqualTo("Hello World"); } } ``` -------------------------------- ### Typical Spring Boot project layout Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows a recommended package structure with a root application class and sub-packages for customer and order domains. ```text com +- example +- myapplication +- Application.java | +- customer | +- Customer.java | +- CustomerController.java | +- CustomerService.java | +- CustomerRepository.java | +- order +- Order.java +- OrderController.java +- OrderService.java +- OrderRepository.java ``` -------------------------------- ### MockMvc test with @SpringBootTest and @AutoConfigureMockMvc Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use @SpringBootTest with @AutoConfigureMockMvc to test the web layer by injecting MockMvc. The example performs a GET request to '/' and expects status 200 and content 'Hello World'. For web layer only, consider @WebMvcTest instead. ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc class MockMvcExampleTests { @Test void exampleTest(@Autowired MockMvc mvc) throws Exception { mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World")); } } ``` -------------------------------- ### Auto-configured Spring REST Docs test with WebTestClient Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use @AutoConfigureRestDocs with @WebFluxTest to automatically configure WebTestClient for Spring REST Docs. Inject WebTestClient with @Autowired and use it as usual. The example shows a test that performs a GET request and documents the result with the 'list-users' identifier. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; @WebFluxTest @AutoConfigureRestDocs class UsersDocumentationTests { @Autowired private WebTestClient webTestClient; @Test void listUsers() { this.webTestClient.get().uri("/").exchange().expectStatus().isOk().expectBody() .consumeWith(document("list-users")); } } ``` -------------------------------- ### Add spring-boot-starter-web for logging (Maven) Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Adds the web starter which transitively includes spring-boot-starter-logging, providing Logback and spring-jcl on the classpath. ```xml org.springframework.boot spring-boot-starter-web ``` -------------------------------- ### Run packaged application with java -jar Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use this command to run a Spring Boot application packaged as an executable jar. The example uses the Maven or Gradle plugin to create the jar. ```bash $ java -jar target/myapplication-0.0.1-SNAPSHOT.jar ``` -------------------------------- ### Auto-configured Spring REST Docs test with Mock MVC Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use @AutoConfigureRestDocs with @WebMvcTest to automatically configure MockMvc for Spring REST Docs. Inject MockMvc with @Autowired and use it as usual. The example shows a test that performs a GET request and documents the result with the 'list-users' identifier. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @WebMvcTest(UserController.class) @AutoConfigureRestDocs class UserDocumentationTests { @Autowired private MockMvc mvc; @Test void listUsers() throws Exception { this.mvc.perform(get("/users").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()) .andDo(document("list-users")); } } ``` -------------------------------- ### Create single instance environment with eb create -s Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use this CLI command to create a single instance environment, avoiding the cost of a load balancer. ```bash eb create -s ``` -------------------------------- ### Configure jOOQ with multiple DataSources Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle This snippet shows how to create a DSLContext for each DataSource when using jOOQ with multiple data sources. The example is a placeholder for the actual configuration, which should be adapted to your specific data sources. ```java // Create a DSLContext for each DataSource // For example: // DSLContext dslContext = DSL.using(dataSource, SQLDialect.POSTGRES); ``` -------------------------------- ### Secure .conf file for init.d service Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Set permissions to read-only for owner and change ownership to root for the .conf file. This is required when root controls the service and the .conf file customizes startup. ```bash $ chmod 400 your-app.conf $ sudo chown root:root your-app.conf ``` -------------------------------- ### Startup Log Output for SampleApplication Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of Spring Boot startup log output showing INFO messages, including the application name, version, and startup duration. The log level can be changed, and startup info logging can be disabled with spring.main.log-startup-info=false. ```log 2019-04-31 13:09:54.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb) 2019-04-31 13:09:54.166 INFO 56603 --- [ main] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy 2019-04-01 13:09:56.912 INFO 41370 --- [ main] .t.TomcatServletWebServerFactory : Server initialized with port: 8080 2019-04-01 13:09:57.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658) ``` -------------------------------- ### Bootstrap a Spring Boot application with SpringApplication.run Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use this main method to start a Spring Boot application. The SpringApplication.run method takes the primary configuration class and command-line arguments. This is the standard entry point for a Spring Boot application. ```java public static void main(String[] args) { SpringApplication.run(MySpringConfiguration.class, args); } ``` -------------------------------- ### Run spring without arguments to display help Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Typing `spring` with no arguments shows a help screen listing available commands. The output includes usage and a list of commands, with more command help available via `spring help`. ```bash $ spring usage: spring [--help] [--version] [] Available commands are: run [options] [--] [args] Run a spring groovy script _... more command help is shown here_ ``` -------------------------------- ### SpringProperty tag example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of exposing a property from the Spring Environment for use within Logback. Uses the tag with scope, name, source, and defaultValue attributes. ```xml ${fluentHost} ... ``` -------------------------------- ### Run a Spring Boot application with runApplication Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use runApplication(*args) as an idiomatic replacement for SpringApplication.run(MyApplication::class.java, *args). Requires kotlin-stdlib and kotlin-reflect on the classpath, and the kotlin-spring plugin to open Spring-annotated classes. ```kotlin import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class MyApplication fun main(args: Array) { runApplication(*args) } ``` -------------------------------- ### Quick-start Spring Boot CLI Groovy application Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Create a simple REST controller in `app.groovy` and run it with `spring run app.groovy`. The first run is slow due to dependency downloads. ```groovy @RestController class ThisWillActuallyRun { @RequestMapping("/") String home() { "Hello World!" } } ``` ```bash $ spring run app.groovy ``` ```text Hello World! ``` -------------------------------- ### Convert existing application to Spring Boot with SpringBootServletInitializer Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle A minimal example of converting an existing Spring application to a deployable war by extending SpringBootServletInitializer and adding @SpringBootApplication. The configure method can be left as returning the application builder, since the class itself is a @Configuration class. ```java @SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { // Customize the application or call application.sources(...) to add sources // Since our example is itself a @Configuration class (via @SpringBootApplication) // we actually don't need to override this method. return application; } } ``` -------------------------------- ### Groovy beans DSL example Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows how to embed bean definitions in a Groovy application script using the beans{} DSL. The example defines a SharedService bean with a message property and uses it in a CommandLineRunner. ```groovy @Configuration(proxyBeanMethods = false) class Application implements CommandLineRunner { @Autowired SharedService service @Override void run(String... args) { println service.message } } import my.company.SharedService beans { service(SharedService) { message = "Hello World" } } ``` -------------------------------- ### spring-boot:exejar with start-class Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Ant task to create an executable jar, specifying the start-class attribute. Includes resources and lib filesets. ```xml ``` -------------------------------- ### Relaxed binding example: @ConfigurationProperties class with prefix 'acme.my-project.person' Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example of a @ConfigurationProperties class with a prefix containing dashes and dots, demonstrating relaxed binding. The class defines a firstName property with getter and setter. ```java @ConfigurationProperties(prefix="acme.my-project.person") public class OwnerProperties { private String firstName; public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } } ``` -------------------------------- ### EnvironmentPostProcessor implementation loading YAML from classpath Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Implements EnvironmentPostProcessor to load a YAML configuration file from the classpath and add it to the Environment. The example adds the 'custom-resource' property source at the end of the list, so keys from other property sources take precedence. The Environment is already prepared with usual property sources, so the file location can be obtained from the environment. A custom implementation may define another order. ```java public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor { private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { Resource path = new ClassPathResource("com/example/myapp/config.yml"); PropertySource propertySource = loadYaml(path); environment.getPropertySources().addLast(propertySource); } private PropertySource loadYaml(Resource path) { if (!path.exists()) { throw new IllegalArgumentException("Resource " + path + " does not exist"); } try { return this.loader.load("custom-resource", path).get(0); } catch (IOException ex) { throw new IllegalStateException("Failed to load yaml configuration from " + path, ex); } } } ``` -------------------------------- ### Tomcat HTTP/2 ALPN error log Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Error logged when starting Tomcat 9.0.x on JDK 8 without native support. The error is not fatal; the application still starts with HTTP/1.1 SSL support. ```log 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. ``` -------------------------------- ### MANIFEST.MF for executable war Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Typical manifest entries for an executable war: Main-Class is WarLauncher and Start-Class is the application's main class. ```text Main-Class: org.springframework.boot.loader.WarLauncher Start-Class: com.mycompany.project.MyApplication ``` -------------------------------- ### Example @ConfigurationProperties class with default values Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example class annotated with @ConfigurationProperties showing a List and an Enum property with non-empty default values. The annotation processor cannot auto-detect default values for Enums and Collections, so manual metadata is required in such cases. ```java @ConfigurationProperties(prefix = "acme.messaging") public class MessagingProperties { private List addresses = new ArrayList<>(Arrays.asList("a", "b")); private ContainerType containerType = ContainerType.SIMPLE; // ... getter and setters public enum ContainerType { SIMPLE, DIRECT } ``` -------------------------------- ### Disable meters with management.metrics.enable Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Disable all meters with an ID starting with 'example.remote'. ```properties management.metrics.enable.example.remote=false ``` -------------------------------- ### Cloud Foundry deployment output Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Example output from cf push showing the buildpack download and application startup. The output includes memory settings and instance status. This is the expected output when deploying a Spring Boot application. ```text Uploading acloudyspringtime... **OK** Preparing to start acloudyspringtime... **OK** -----> Downloaded app package (**8.9M**) -----> Java Buildpack Version: v3.12 (offline) | https://github.com/cloudfoundry/java-buildpack.git#6f25b7e -----> Downloading Open Jdk JRE 1.8.0_121 from https://java-buildpack.cloudfoundry.org/openjdk/trusty/x86_64/openjdk-1.8.0_121.tar.gz (found in cache) Expanding Open Jdk JRE to .java-buildpack/open_jdk_jre (1.6s) -----> Downloading Open JDK Like Memory Calculator 2.0.2_RELEASE from https://java-buildpack.cloudfoundry.org/memory-calculator/trusty/x86_64/memory-calculator-2.0.2_RELEASE.tar.gz (found in cache) Memory Settings: -Xss349K -Xmx681574K -XX:MaxMetaspaceSize=104857K -Xms681574K -XX:MetaspaceSize=104857K -----> Downloading Container Certificate Trust Store 1.0.0_RELEASE from https://java-buildpack.cloudfoundry.org/container-certificate-trust-store/container-certificate-trust-store-1.0.0_RELEASE.jar (found in cache) Adding certificates to .java-buildpack/container_certificate_trust_store/truststore.jks (0.6s) -----> Downloading Spring Auto Reconfiguration 1.10.0_RELEASE from https://java-buildpack.cloudfoundry.org/auto-reconfiguration/auto-reconfiguration-1.10.0_RELEASE.jar (found in cache) Checking status of app 'acloudyspringtime'... 0 of 1 instances running (1 starting) ... 0 of 1 instances running (1 starting) ... 0 of 1 instances running (1 starting) ... 1 of 1 instances running (1 running) App started ``` -------------------------------- ### Run exploded executable jar with JarLauncher Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Unpack the executable jar and run it using the JarLauncher. This is slightly faster on startup than running from an unexploded archive, but at runtime there are no differences. ```bash $ jar -xf myapp.jar $ java org.springframework.boot.loader.JarLauncher ``` -------------------------------- ### Custom InfoContributor bean adding an example entry Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Register a Spring bean implementing InfoContributor to contribute custom application information. The contribute method adds a detail named 'example' with a map containing a key-value pair. When the info endpoint is reached, the response includes this additional entry. ```java import java.util.Collections; import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component; @Component public class ExampleInfoContributor implements InfoContributor { @Override public void contribute(Info.Builder builder) { builder.withDetail("example", Collections.singletonMap("key", "value")); } } ``` -------------------------------- ### Configure Two DataSources with application.properties Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows the application.properties configuration for the two data sources defined in the previous example. The first data source uses HikariCP settings under 'app.datasource.first.configuration', and the second uses BasicDataSource settings under 'app.datasource.second'. ```properties app.datasource.first.url=jdbc:mysql://localhost/first app.datasource.first.username=dbuser app.datasource.first.password=dbpass app.datasource.first.configuration.maximum-pool-size=30 app.datasource.second.url=jdbc:mysql://localhost/second app.datasource.second.username=dbuser app.datasource.second.password=dbpass app.datasource.second.max-total=30 ``` -------------------------------- ### Get help for a specific command with spring help run Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Use `spring help run` to display detailed help for the `run` command, including options like `--autoconfigure`, `--classpath`, and `--watch`. ```bash $ spring help run spring run - Run a spring groovy script usage: spring run [options] [--] [args] Option Description ------ ----------- --autoconfigure [Boolean] Add autoconfigure compiler transformations (default: true) --classpath, -cp Additional classpath entries --no-guess-dependencies Do not attempt to guess dependencies --no-guess-imports Do not attempt to guess imports -q, --quiet Quiet logging -v, --verbose Verbose logging of dependency resolution --watch Watch the specified file for changes ``` -------------------------------- ### Supply spring.application.json as command line argument Source: https://docs.spring.io/spring-boot/docs/2.2.7.RELEASE/reference/htmlsingle Shows how to pass JSON configuration via the --spring.application.json command line argument. ```shell $ java -jar myapp.jar --spring.application.json='{"name":"test"}' ```