Card 03/ 06

ExampleDifficulty: Intermediate1 min

Embedded Servers: A Web Server Inside Your Own Jar

java -jar starts the application and its server together, with nothing installed separately.

An embedded server is a web server that ships as a library inside your application, so starting the application starts the server too. Spring Boot uses one by default: the jar it builds (a single file holding the application and all its libraries) listens on a port as soon as it runs.

The code below starts an application and asks the context which port its web server is listening on:

java
var context = SpringApplication.run(EmbeddedServerDemo.class, args);
var webContext = (WebServerApplicationContext) context;
int port = webContext.getWebServer().getPort();
System.out.println("Listening on port " + port + ", no server installed separately.");
text
Listening on port 8080, no server installed separately.
run in a container: the whole server lives inside the jar

No Tomcat was installed on that machine and no server was configured outside the application. The server is a dependency like any other, brought in by spring-boot-starter-web, and auto-configuration, Boot's habit of creating beans for whatever is on the classpath, started it on the default port, 8080.

The older approach packages the application as a WAR file (a web archive that an external server such as Tomcat loads) and deploys it into a server that already runs on the target machine. It still works, and some organisations still deploy that way, but it is no longer the default.

So deploying a Boot application usually means copying one jar and running java -jar, because the server travels with it.