Introduction
Spring Boot initial project (which is generated from spring starter) project comes with an embedded server i.e tomcat. The default port of embedded tomcat is 8080
. Changing the default port for the embedded server has multiple ways. Let's find out how.
Using property files
The easiest way to customize Spring Boot embedded server port is by overriding the values of the default properties.
Updating application properties
We can change the embedded tomcat server port by changing the value of server.port
property. By default, its value is 8080
. After changing the value, application.properties
file should look like below:
server.port = 9099
Updating application yaml
If yaml configuration file used in the application, then we need to make the following change in application.yml
file:
server:
port : 9099
Using Command Line arguments
We can pass the argument --server.port=port_number
while running the application using command line:
java -jar spring-boot-app.jar --server.port=9099
We can change the server port by passing the System property as well.
java -jar -Dserver.port=9099 spring-boot-app.jar
Using Programatic approach
Customizing the embedded server configuration
If we need to programmatically configure embedded servlet container, we can register a Spring bean that implements the WebServerFactoryCustomizer
interface. WebServerFactoryCustomizer
provides access to the ConfigurableServletWebServerFactory
, which includes numerous customization setter methods.
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomizationBean implements WebServerFactoryCustomizer<configurableservletwebserverfactory> {
@Override
public void customize(ConfigurableServletWebServerFactory server) {
server.setPort(9099);
}
}
Setting the property in Application class
Alternatively we can configure the server port programmatically by setting the specific property while starting the application in main (@SpringBootApplication) class:
@SpringBootApplication
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(SpringBootApplication.class);
application.setDefaultProperties(Collections.singletonMap("server.port", "9099"));
application.run(args);
}
}
Please refer spring io documentation on how to change the http port and Feature customizing embedded containers for more details.
No comments :
Post a Comment