Thursday, 13 June 2019

How to change the default port in spring boot application programmatically? | Spring Boot tutorial

🎯 Never Miss a Java Hack!

Level up your Spring Boot skills with weekly tutorials on Ram N Java. Join our coding community today!

SUBSCRIBE NOW

Changing the Spring Boot Port Programmatically

By default, Spring Boot applications start on port 8080. While changing this in a properties file is common, there are many scenarios—like building dynamic microservices—where you might need to change it directly in your Java code. This guide makes it simple!

Why Change the Port in Code?

Setting the port programmatically gives you ultimate control. You can calculate the port at runtime, read it from a database, or even find an available port automatically. This is especially useful for developers running multiple local instances of the same service.

The Main Methods

There are two primary ways to handle this in your Spring Boot project:

  • Using WebServerFactoryCustomizer: This is the modern, flexible way to customize the server. You create a component that tells Spring exactly how to configure the embedded server before it starts.
  • Using System Properties: You can set the port within your main method before calling SpringApplication.run(). It’s a quick and dirty way to override settings globally.

Beginner Tip: Keep it Dynamic

If you're worried about port conflicts, you can set the port to 0. This tells Spring Boot to find any randomly available port on your machine. It’s a great trick for integration testing or when you don't want to manually manage port numbers!

Remember: Any changes made programmatically will typically override what is written in your application.properties file.


Continue Your Spring Boot Journey

Check out these other helpful tutorials from the Ram N Java channel:

1 comment:

  1. This is an awesome post. Really very informative and creative contents. Visit my website to get best Information About Modular kitchen in Ghaziabad.
    Modular kitchen in Ghaziabad
    Modular Kitchen in Noida

    ReplyDelete

Tutorials