方式一
在spring boot的web 工程中,可以使用内置的web container、有时需要修改服务端口,可以通过配置类和@Configuration注解来完成。
// MyConfiguration.java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfiguration {
@Value("${tomcatport:8090}")
private int port;
@Bean
public EmbeddedServletContainerFactory servletContainer(){
return new TomcatEmbeddedServletContainerFactory(this.port);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
这里使用@Value注解,为tomcatport赋予8090的端口。
可以进入EmbeddedServletContainerFactory类查看实现的处理。
方式二
在应用的application.properties或者yml配置文件中,添加配置项。
如:
#指定web 的 contex path
server.contextPath=/myapp
#指定服务端口
server.port=8080

本文介绍了两种在SpringBoot项目中设置服务端口的方法:一是通过配置类和@Configuration注解;二是直接在application.properties或yml配置文件中指定。这些方法帮助开发者灵活地调整应用程序的运行端口。
845

被折叠的 条评论
为什么被折叠?



