Tuesday 27 August 2019

How to configure port for a spring boot application?


By default spring boot application runs on port 8080. If you want to customize the port of spring boot application, you can do that by setting the property 'server.port'.

Example
server.port=1234

Approach 1: Adding the property server.port in application.properties.
Create a maven project like below.


application.properties
server.port=1234


HomeController.java
package com.sample.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

	@RequestMapping("/")
	public String homePage() {
		return "Welcome to Spring boot Application Development";
	}

}


App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
	public static void main(String[] args) {

		SpringApplication.run(App.class, args);
	}
}


Run App.java and open the url ‘http://localhost:1234/’.

Approach 2: By passing the vm argument '-Dserver.port=5678'
Right click on App.java.


Run As -> Run Configurations.



Click on Arguments tab and inder VM arguments: section paste below line.
-Dserver.port=5678

Click on Run button.

Open the url 'http://localhost:5678/' in browser, you can see below kind of screen.

Step 3: Configuring programmatically.

Map<String, Object> props = new HashMap<>();
props.put("server.port", 1234);

new SpringApplicationBuilder()
    .sources(App.class)               
    .properties(props)
    .run(args);

Above snippet runs the application on port 1234.

If you set server.port to 0, then the application runs on random port.
server.port=0

Approach 4: By setting the system property ‘server.port’.
System.setProperty("server.port","1234");

You can download the complete working application from this link.

Previous                                                    Next                                                    Home

No comments:

Post a Comment