Sometimes we may need to start more than one springboot, and the Springboot default port number is 8080, so at this point we need to modify the default ports of Springboot. There are two ways to modify the default port for Springboot. Here are the two ways to talk about each one.
Modify Application.properties
The first way we only need to add such a sentence in application.properties: server.port=8004. Why is this way possible to modify the default port for Springboot? Because there is such a class in Springboot: Serverproperties. We can take a look at this class in general:
[Java]View PlainCopy
- @ConfigurationProperties (prefix = "server", ignoreunknownfields = true)
- public class serverproperties
- implements embeddedservletcontainercustomizer, environmentaware, ordered {
-
- /** 
- * server http port.
- */
- private integer port;
In this class there is a @configurationproperties annotation that reads the value of the springboot default configuration file application.properties into the bean. This defines a server prefix and a port field, so the value of Server.port is read from Application.properties when Springboot is started. Let's take a look down:
[Java]View PlainCopy
- @Override
- public void Customize (Configurableembeddedservletcontainer container) {
- if (getport () = null) {
- Container.setport (Getport ());
- }
Here is a customize method, which will give Springboot the port number to read.
Implementation Embeddedservletcontainercustomizer we saw that the port number was set in the Customize method, And this method is in Embeddedservletcontainercustomizer this interface, so we can implement this interface, to change the default port number of Springboot. The specific code is as follows:
[Java]View PlainCopy
- @RestController
- @EnableAutoConfiguration
- @ComponentScan
- Public class Firstexample implements Embeddedservletcontainercustomizer {
- @RequestMapping ("/first.do")
- String Home () {
- return "Hello world! World Hello! O (∩_∩) o haha ~!!! I'm not too good! ";
- }
- public static void Main (string[] args) {
- Springapplication.run (firstexample. class, args);
- }
- @Override
- public void Customize (Configurableembeddedservletcontainer configurableembeddedservletcontainer) {
- Configurableembeddedservletcontainer.setport (8003);
- }
- }
Then when you start Springboot, you find that the port number is changed to 8003.
Using command-line arguments if you just want to modify the port number at startup, you can modify the port number with the command-line arguments. The configuration is as follows: Java-jar after packaging Springboot.jar--server.port=8000 using the virtual machine parameters you can also put the configuration of the modified port number in the JVM parameters. The configuration is as follows:-dserver.port=8009. The port number that was started is changed to 8009. Reprinted from: 53433592
"Reprint" Springboot Modify the default port number