• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Boot – How to Change Embedded Tomcat default port

April 17, 2017 by javainterviewpoint 2 Comments

By default, the embedded tomcat server of Spring Boot application will be starting at port 8080. In this article, we will learn how to change embedded Tomcat default port using one of the following approaches

  1. Using application.properties or application.yml
  2. Implementing EmbeddedServletContainerCustomizer interface
  3. Using SpringApplication class
  4. Change port directly through command line

Let’s assume we have a simple Spring Boot Hello World application like below.

Folder Structure:

Spring Boot Hello World

  1. Create a simple Maven Project “SpringBootTutorial” by selecting maven-archetype-quickstart  and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the POM.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0	http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
    
     <groupId>com.javainterviewpoint</groupId>
     <artifactId>SpringBootTutorial</artifactId>
     <version>0.0.1-SNAPSHOT</version>
    
     <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.5.1.RELEASE</version>
     </parent>
     
     <dependencies>
       <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
     </dependencies>
     
     <build>
       <plugins>
         <plugin>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
       </plugins>
     </build>
     </project>
  3. Create the Java classes HelloWorld.java under com.javainterviewpoint folder.

Other interesting articles which you may like …

  • Spring Boot Hello World Example with Maven
  • How to Create Deployable WAR SpringBootServletInitializer
  • Spring Boot CommandLineRunner and ApplicationRunner
  • Spring Boot CRUDRepository Example- Spring Data JPA
  • Fix missing src/main/java folder in Eclipse Maven Project – 2 build path entries are missing
  • Spring MVC CRUD Example with MySql + JdbcTemplate
  • RESTful Java Client With Jersey Client
  • RESTEasy Hello World Example with Apache Tomcat
  • RESTful Java client with RESTEasy client
  • Spring RESTful Web Services Hello World XML Example
  • Springfox Swagger 2 for Spring RESTful Web Services

The spring-boot-starter-parent is a special starter, it provides useful Maven defaults. Since we are developing a web application, we also need to add spring-boot-starter-web dependency.This will add dependencies such Tomcat, Jackson, Spring boot etc which are required for our application.

HelloWorld.java

Place HelloWorld.java under com.javainterviewpoint folder

package com.javainterviewpoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@SpringBootApplication
public class HelloWorld {

    @RequestMapping("/")
    String hello() {
        return "Hello World! JavaInterviewPoint";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(HelloWorld.class, args);
    }
}

We have added the below annotations in our HelloWorld class

  • @RestController – This annotation is a stereotype annotation, this annotation tells spring to render the result back to the caller.
  • @RequestMapping – This annotation will any HTTP request with the path “/” should be mapped to the hello() method
  • @EnableAutoConfiguration – This annotation tells the Spring Boot to configure the application based on the dependencies added. Since spring-boot-starter-web has added Tomcat and Spring MVC, auto-configuration will setup a web based application.

Upon execution, we will have the application started with the below console

 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.1.RELEASE)

2017-02-24 15:14:04.568  INFO 1112 --- [           main] com.javainterviewpoint.HelloWorld        : Starting HelloWorld on DA56CZ8VD02 with PID 1112 (C:\Jackson\sts\JIPWorkspace\SpringBootTutorial\target\classes started by xbbl47m in C:\Jackson\sts\JIPWorkspace\SpringBootTutorial)
2017-02-24 15:14:04.570  INFO 1112 --- [           main] com.javainterviewpoint.HelloWorld        : No active profile set, falling back to default profiles: default
2017-02-24 15:14:04.622  INFO 1112 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot[email protected]2e3593ab: startup date [Fri Feb 24 15:14:04 IST 2017]; root of context hierarchy
2017-02-24 15:14:05.432  INFO 1112 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-02-24 15:14:05.533  INFO 1112 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-02-24 15:14:05.933  INFO 1112 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-02-24 15:14:05.952  INFO 1112 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-02-24 15:14:05.953  INFO 1112 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-02-24 15:14:06.059  INFO 1112 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-02-24 15:14:06.059  INFO 1112 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1439 ms
2017-02-24 15:14:06.206  INFO 1112 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-02-24 15:14:06.210  INFO 1112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-02-24 15:14:06.210  INFO 1112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-02-24 15:14:06.210  INFO 1112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-02-24 15:14:06.210  INFO 1112 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-02-24 15:14:06.522  INFO 1112 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot[email protected]2e3593ab: startup date [Fri Feb 24 15:14:04 IST 2017]; root of context hierarchy
2017-02-24 15:14:06.614  INFO 1112 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.javainterviewpoint.HelloWorld.hello()
2017-02-24 15:14:06.619  INFO 1112 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-02-24 15:14:06.619  INFO 1112 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-02-24 15:14:06.654  INFO 1112 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-24 15:14:06.654  INFO 1112 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-24 15:14:06.700  INFO 1112 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-02-24 15:14:06.938  INFO 1112 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-02-24 15:14:07.016  INFO 1112 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-02-24 15:14:07.021  INFO 1112 --- [           main] com.javainterviewpoint.HelloWorld        : Started HelloWorld in 2.832 seconds (JVM running for 3.398)

How to Change Embedded Tomcat default port

We will change embedded tomcat default port from 8080 to 9090

1. Using application.properties or application.yml

Create the application.properties file under “src\main\resources\application.properties” and add the below entry

server.port = 9090

If not create application.yml file under “src\main\resources\application.yml” and add the below entry

server:
       port: 9090

After creating any one of the files, start the spring boot app, you will be able to see that the server has started at 9090 port.

Change Embedded Tomcat default port

2. Implementing EmbeddedServletContainerCustomizer interface

Embedded Servlet containers port can be changed by implementing the EmbeddedServletContainerCustomizer interface and overriding the customize() method

package com.javainterviewpoint;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.stereotype.Component;

@Component
public class AppContainerCustomizer implements EmbeddedServletContainerCustomizer {
 
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) 
    {
        container.setPort(9090);
    }
}

3. Using SpringApplication class

package com.javainterviewpoint;

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@EnableAutoConfiguration
@SpringBootApplication
public class HelloWorld
{

    @RequestMapping("/")
    String hello()
    {
        return "Hello World! JavaInterviewPoint";
    }

    public static void main(String[] args) throws Exception
    {
        //Create object for SpringApplication
        SpringApplication springApplication = new SpringApplication(HelloWorld.class);
        //create a map and add property SERVER_PORT
        Map<String, Object> server = new HashMap<String, Object>();
        server.put("SERVER_PORT", "9090");
        //Overriding the defaults
        springApplication.setDefaultProperties(server);
        //Running our application
        springApplication.run(args);
    }
}
  • We have created a new object for the SpringApplication class, passing our HelloWorld.class as an argument.
  • Create a new Map and set the value to the property “SERVER_PORT”, pass our map as an argument to the setDefaultProperties() method of the SpringApplication class and run the application.

4. Change port directly through command line

We can also change the embedded tomcat default port directly using java command. While executing the jar through command line we need to add an additional parameter “–server.port=9090”, to change the port to 9090.

java -jar SpringBootTutorial-0.0.1-SNAPSHOT.jar --server.port=9090

Filed Under: J2EE, Java, Spring, Spring Boot, Spring Tutorial Tagged With: Change Embedded Tomcat default port

Comments

  1. devops online training says

    May 30, 2017 at 11:24 am

    Thank you very much ! You have cleared out the difference between them.

    Reply
  2. Ravikira says

    May 30, 2018 at 4:17 pm

    Excellent..!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·