Spring Boot: Bootstrapping a web server
Spring Boot auto-configures an embedded Tomcat server the moment spring-boot-starter-web is on the classpath. A single @SpringBootApplication annotation on your main class combines @Configuration, @EnableAutoConfiguration, and @ComponentScan, getting a production-capable web server running with zero XML. This article covers project setup, the application entry point, and changing the default port.
When the jar present in class path, and when the application it automatically configures and starts a Tomcat server that is embedded inside this jar.
Bootstrapping a web server
-
Add
maven dependency to your project, for the below example we are using version 2.7.6. For the latest version of the jar available, check maven repository herespring-boot-starter-webspring-boot-starter-web -
Next create a Java class with
method and annotate the class withmain() .@SpringBootApplication
By declaring the class with annotation, it automatically configures the app, and applies component scan on the current package and sub package classes. This is equivalent to annotating the class with@SpringBootApplication ,@Configuration , and@EnableAutoConfiguration .@ComponentScan - When you launch the class, this automatically starts the embedded tomcat and binds to port 8080, which is the default port.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.6</version>
</dependency>
package io.cscode.springboot.web;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootstrapWebServer {
public static void main(String[] args) {
SpringApplication.run(BootstrapWebServer.class, args);
}
}
Note: Note that in the above example, we did not specify any spring profile, so it uses the default profile with default values.
INFO 1012 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
How to change default port number for web server
As you see in above example, Tomcat server started with default port number 8080,
if you want to change the port number, you can suply server.port
-
You can supply
as JVM argument,server.port-Dserver.port=9090 -
You can supply
as application argument,server.port--server.port=9090 -
You can supply it through Spring's
file orapplication.properties file.application.yml
--server.portBelow is an example specifying port number as 9090 in application.properties.
server.port=9090
Below is an example specifying port number as 9090 in application.yaml.
server:
port: 9090