### Classpath Index File Example Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Shows the required format for BOOT-INF/classpath.idx: each line starts with dash space and contains a quoted jar name in the order they should be added to the classpath. ```yaml - "BOOT-INF/lib/dependency2.jar" - "BOOT-INF/lib/dependency1.jar" ``` -------------------------------- ### Quick-start Spring CLI example: app.groovy Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Create this Groovy file to test your Spring Boot CLI installation. It defines a REST controller that returns 'Hello World!' at the root path. ```groovy @RestController class ThisWillActuallyRun { @RequestMapping("/") String home() { "Hello World!" } } Copy to clipboard ``` -------------------------------- ### Install Spring Boot CLI with SDKMAN! Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Use these commands to install the Spring Boot CLI via SDKMAN! and verify the installation. The output shows the installed version. ```bash $ sdk install springboot $ spring --version Spring Boot v2.5.3 Copy to clipboard ``` -------------------------------- ### Start application with active profiles Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Command to start the application with the 'production' profile, which activates 'production', 'proddb', and 'prodmq' profiles. ```bash --spring.profiles.active=production ``` -------------------------------- ### BufferingApplicationStartup example Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Configures SpringApplication to use BufferingApplicationStartup with a buffer size of 2048 for startup tracking. ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication application = new SpringApplication(MyApplication.class); application.setApplicationStartup(new BufferingApplicationStartup(2048)); application.run(args); } } ``` -------------------------------- ### Create systemd service unit file myapp.service Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example systemd service unit file for a Spring Boot application installed in /var/myapp. Remember to change Description, User, and ExecStart fields. ExecStart does not declare the action command, so 'run' is used by default. ```ini [Unit] Description=myapp After=syslog.target [Service] User=myapp ExecStart=/var/myapp/myapp.jar SuccessExitStatus=143 [Install] WantedBy=multi-user.target ``` -------------------------------- ### Run the application with mvn spring-boot:run and view output Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Run this command from the root project directory to start the application. The expected output shows the Spring Boot banner and a log line indicating the application started. After starting, open localhost:8080 to see the response. ```bash $ mvn spring-boot:run . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.5.3) ....... . . . ....... . . . (log output here) ....... . . . ........ Started MyApplication in 2.222 seconds (JVM running for 6.514) ``` -------------------------------- ### RemoteSpringApplication startup log output Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example log output from starting a remote Spring Boot application with RemoteSpringApplication, showing startup messages, warnings about insecure connection, and LiveReload server startup. ```log 2015-06-10 18:25:06.632 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Starting RemoteSpringApplication on pwmbp with PID 14938 (/Users/pwebb/projects/spring-boot/code/spring-boot-project/spring-boot-devtools/target/classes started by pwebb in /Users/pwebb/projects/spring-boot/code) 2015-06-10 18:25:06.671 INFO 14938 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2a17b7b6: startup date [Wed Jun 10 18:25:06 PDT 2015]; root of context hierarchy 2015-06-10 18:25:07.043 WARN 14938 --- [ main] o.s.b.d.r.c.RemoteClientConfiguration : The connection to http://localhost:8080 is insecure. You should use a URL starting with 'https://'. 2015-06-10 18:25:07.074 INFO 14938 --- [ main] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729 2015-06-10 18:25:07.130 INFO 14938 --- [ main] o.s.b.devtools.RemoteSpringApplication : Started RemoteSpringApplication in 0.74 seconds (JVM running for 1.105) ``` -------------------------------- ### Expected output from Spring CLI example Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle After running the example, open localhost:8080 in a browser to see this output. ```text Hello World! ``` -------------------------------- ### List installed Spring Boot CLI versions with SDKMAN! Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Run this command to list installed Spring Boot CLI versions. The output shows the 'dev' instance and the installed version 2.5.3, with markers indicating local, installed, and currently in use. ```bash $ sdk ls springboot ================================================================================ Available Springboot Versions ================================================================================ > + dev * 2.5.3 ================================================================================ + - local version * - installed > - currently in use ================================================================================ Copy to clipboard ``` -------------------------------- ### Start service with service command Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Start the Spring Boot application as an init.d service using the service command on Debian-based systems. ```bash $ service myapp start ``` -------------------------------- ### Set init.d service to start automatically Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Use update-rc.d to configure the service to start automatically on Debian systems. ```bash $ update-rc.d myapp defaults ``` -------------------------------- ### YAML list example Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example YAML list that is flattened into property keys with [index] dereferencers. ```yaml my: servers: - dev.example.com - another.example.com ``` -------------------------------- ### Configure spring.integration.jdbc.initialize-schema (YAML) Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle YAML equivalent of the Properties example for JDBC schema initialization. ```yaml spring: integration: jdbc: initialize-schema: "always" ``` -------------------------------- ### Example layers.idx file Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Defines the layer index for a Spring Boot jar, listing layers and their contents. The order of layers matches the order they should be added to the Docker/OCI image. This example shows the default layers: dependencies, spring-boot-loader, snapshot-dependencies, and application. ```plaintext - "dependencies": - BOOT-INF/lib/library1.jar - BOOT-INF/lib/library2.jar - "spring-boot-loader": - org/springframework/boot/loader/JarLauncher.class - org/springframework/boot/loader/jar/JarEntry.class - "snapshot-dependencies": - BOOT-INF/lib/library3-SNAPSHOT.jar - "application": - META-INF/MANIFEST.MF - BOOT-INF/classes/a/b/C.class ``` -------------------------------- ### Install Spring Boot CLI dev instance with SDKMAN! Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Use these commands to install a local 'dev' instance of the Spring Boot CLI that points to your target build location. This is useful for developing CLI features. The output shows the version as 'Spring CLI v2.5.3'. ```bash $ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.5.3-bin/spring-2.5.3/ $ sdk default springboot dev $ spring --version Spring CLI v2.5.3 Copy to clipboard ``` -------------------------------- ### Testing with a Mock Environment using @AutoConfigureMockMvc Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Shows how to configure MockMvc with @AutoConfigureMockMvc in a @SpringBootTest to test web endpoints without starting a server. The example performs a GET request and verifies the status and content. ```java import org.junit.jupiter.api.Test; 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 MyMockMvcTests { @Test void exampleTest(@Autowired MockMvc mvc) throws Exception { mvc.perform(get("/")).andExpect(status().isOk()).andExpect(content().string("Hello World")); } } ``` -------------------------------- ### Inject MongoTemplate to access MongoDB Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Inject the auto-configured MongoTemplate bean to access MongoDB collections. This example shows a component that gets a collection using MongoTemplate. ```java import com.mongodb.client.MongoCollection; import org.bson.Document; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Component; @Component public class MyBean { private final MongoTemplate mongoTemplate; public MyBean(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } // ... public MongoCollection someMethod() { return this.mongoTemplate.getCollection("users"); } } ``` -------------------------------- ### List capabilities with spring init --list Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Lists available dependencies and project types from start.spring.io. The output shows available dependencies and project types. ```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) ... ``` -------------------------------- ### Initialize a new project with spring init Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Creates a new project using start.spring.io. The example creates a Maven-based project with web and data-jpa dependencies. ```bash $ spring init --dependencies=web,data-jpa my-project Using service at https://start.spring.io Project extracted to '/Users/developer/example/my-project' ``` -------------------------------- ### Inject MongoDatabaseFactory to access MongoDB Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Inject the auto-configured MongoDatabaseFactory to access a MongoDB database. By default, it connects to mongodb://localhost/test. This example shows a component that gets a collection from the database. ```java import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.springframework.data.mongodb.MongoDatabaseFactory; import org.springframework.stereotype.Component; @Component public class MyBean { private final MongoDatabaseFactory mongo; public MyBean(MongoDatabaseFactory mongo) { this.mongo = mongo; } // ... public MongoCollection someMethod() { MongoDatabase db = this.mongo.getMongoDatabase(); return db.getCollection("users"); } } ``` -------------------------------- ### Run the Spring CLI example Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Run the app.groovy file using the Spring Boot CLI. The first run is slow because dependencies are downloaded; subsequent runs are quicker. ```bash $ spring run app.groovy Copy to clipboard ``` -------------------------------- ### Enable command-line completion for Spring Boot CLI Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Source the completion script for bash or zsh. The example shows sourcing the script from the SDKMAN! installation and then pressing TAB to see available commands. ```bash $ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring $ spring grab help jar run test version Copy to clipboard ``` -------------------------------- ### Calling RSocket services with RSocketRequester Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example of injecting RSocketRequester.Builder into a service and using it to establish a TCP connection and make a request. The builder is a prototype bean, so each injection point gets a new instance. ```java import reactor.core.publisher.Mono; import org.springframework.messaging.rsocket.RSocketRequester; import org.springframework.stereotype.Service; @Service public class MyService { private final RSocketRequester rsocketRequester; public MyService(RSocketRequester.Builder rsocketRequesterBuilder) { this.rsocketRequester = rsocketRequesterBuilder.tcp("example.org", 9898); } public Mono someRSocketCall(String name) { return this.rsocketRequester.route("user").data(name).retrieveMono(User.class); } } Expanded folded textCopy to clipboard ``` -------------------------------- ### Startup failure message for port 8080 in use Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example error message shown when a web application fails to start because port 8080 is already in use. The message suggests identifying and stopping the process or configuring another port. ```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. ``` -------------------------------- ### Example volume mount structure for multiple config trees Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Shows a directory structure with multiple config trees under a parent folder, used with the wildcard import. ```text etc/ config/ dbconfig/ db/ username password mqconfig/ mq/ username password ``` -------------------------------- ### WebTestClient with @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Use this test to start a full running server on a random port. The @LocalServerPort annotation can inject the actual port, and WebTestClient is autowired to resolve relative links to the running server. This setup requires spring-webflux on the classpath. ```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.test.web.reactive.server.WebTestClient; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class MyRandomPortWebTestClientTests { @Test void exampleTest(@Autowired WebTestClient webClient) { webClient .get().uri("/") .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo("Hello World"); } } ``` -------------------------------- ### Spring CLI help for run command Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Shows 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 ``` -------------------------------- ### Enable systemd service with systemctl Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Use systemctl enable myapp.service to flag the application to start automatically on system boot. ```bash $ systemctl enable myapp.service ``` -------------------------------- ### Typical MANIFEST.MF for executable war Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Specifies the Main-Class as WarLauncher and Start-Class as the application's main class. Required for executable war files. ```text Main-Class: org.springframework.boot.loader.WarLauncher Start-Class: com.mycompany.project.MyApplication ``` -------------------------------- ### Inject WebClient.Builder to create a WebClient and call a REST service Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Shows a typical Spring service that injects the auto-configured WebClient.Builder, sets a base URL, and uses the WebClient to perform a GET request. The builder is stateful, so changes affect all clients created from it. This example uses Reactor Netty by default. ```java import org.neo4j.cypherdsl.core.Relationship.Details; import reactor.core.publisher.Mono; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; @Service public class MyService { private final WebClient webClient; public MyService(WebClient.Builder webClientBuilder) { this.webClient = webClientBuilder.baseUrl("https://example.org").build(); } public Mono
someRestCall(String name) { return this.webClient.get().uri("/{name}/details", name).retrieve().bodyToMono(Details.class); } } ``` -------------------------------- ### Gradle setup for Log4j2 with module replacement Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Gradle dependencies using module replacement to replace the default logging starter with the Log4j2 starter. ```groovy dependencies { implementation "org.springframework.boot:spring-boot-starter-log4j2" modules { module("org.springframework.boot:spring-boot-starter-logging") { replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback") } } } ``` -------------------------------- ### Install CLI extension with spring install Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Installs a CLI extension using artifact coordinates in the format group:artifact:version. Dependencies are also installed. ```bash $ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE ``` -------------------------------- ### Check Java Installation with java -version Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Run this command in a terminal to verify that Java SDK v1.8 or higher is installed before installing Spring Boot. The output shows the installed Java version. ```bash $ java -version Copy to clipboard ``` -------------------------------- ### Create Gradle project with spring init Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Creates a Gradle project with Java 8 and war packaging using the init command. The output shows the service URL and saved file. ```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' ``` -------------------------------- ### AcmeProperties configuration properties class with Javadoc Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example of a @ConfigurationProperties class for the 'acme' namespace, showing field Javadoc for documentation. Use plain text in Javadoc since it is not processed before being added to JSON. For boolean fields, start description with 'Whether' or 'Enable'; for collections, use 'Comma-separated list'; use java.time.Duration instead of long and describe default unit if not milliseconds. ```java import java.time.Duration; import org.springframework.boot.context.properties.ConfigurationProperties; @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 ... public boolean isCheckLocation() { return this.checkLocation; } public void setCheckLocation(boolean checkLocation) { this.checkLocation = checkLocation; } public Duration getLoginTimeout() { return this.loginTimeout; } public void setLoginTimeout(Duration loginTimeout) { this.loginTimeout = loginTimeout; } } ``` -------------------------------- ### Example volume mount structure for configuration tree Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Shows the directory structure of a mounted volume with configuration files. The filenames become property keys and contents become values. ```text etc/ config/ myapp/ username password ``` -------------------------------- ### Java class MyProperties with Map for manual hints Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example of a @ConfigurationProperties class with a Map property named 'contexts'. Used to demonstrate providing value hints for the map keys using the 'my.contexts.keys' hint name. ```java import java.util.Map; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("my") public class MyProperties { private Map contexts; // getters/setters ... public Map getContexts() { return this.contexts; } public void setContexts(Map contexts) { this.contexts = contexts; } } ``` -------------------------------- ### SpringApplication.run example Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle A minimal Spring Boot application using @SpringBootApplication and SpringApplication.run to bootstrap the application from the main method. ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` -------------------------------- ### Install Spring Boot CLI with Scoop Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Use these commands to install the Spring Boot CLI on Windows via Scoop. The installation places 'spring' in ~/scoop/apps/springboot/current/bin. ```powershell > scoop bucket add extras > scoop install springboot ``` -------------------------------- ### Maven setup for Log4j2 with starters Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Maven dependencies to exclude the default logging starter and include the Log4j2 starter, as recommended for using Log4j2 with Spring Boot. ```xml org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-logging org.springframework.boot spring-boot-starter-log4j2 ``` -------------------------------- ### Install Spring Boot CLI with Homebrew Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Use these commands to install the Spring Boot CLI on macOS via Homebrew. The installation places the 'spring' command in /usr/local/bin. ```bash $ brew tap spring-io/tap $ brew install spring-boot Copy to clipboard ``` -------------------------------- ### Setting server properties in application.properties Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Shows how to set server.port and server.address in an application.properties file. ```properties server.port=9090 server.address=127.0.0.1 ``` -------------------------------- ### Prometheus scrape_config example Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Example scrape_config to add to prometheus.yml for scraping Spring Boot actuator endpoint. ```yaml scrape_configs: - job_name: 'spring' metrics_path: '/actuator/prometheus' static_configs: - targets: ['HOST:PORT'] ``` -------------------------------- ### Typical MANIFEST.MF for executable jar Source: https://docs.spring.io/spring-boot/docs/2.5.3/reference/htmlsingle Specifies the Main-Class as JarLauncher and Start-Class as the application's main class. Required for executable jar files. ```text Main-Class: org.springframework.boot.loader.JarLauncher Start-Class: com.mycompany.project.MyApplication ```