spring boot本身内置tomcat,我们一般只需要引入tomcat的依赖即可.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
但是默认的端口有可能被占用了,提示如下信息
Description:
The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.
Action:
Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.
别急,我们可以自定义端口,有三种方法:
1.在配置文件中设置:
使用application.properties
server.port=8888
使用application.yml
server:
port: 8888
- 直接自定义ConfigurableEmbeddedServletContainer.通过自己注册TomcatEmbeddedServletContainerFactory,
JettyEmbeddedServletContainerFactory或UndertowEmbeddedServletContainerFactory
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
factory.setPort(9000);
factory.setSessionTimeout(10, TimeUnit.MINUTES);
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/notfound.html");
return factory;
}
- Spring boot中自定义端口需要入口类实现ConfigurableEmbeddedServletContainer接口.如下代码
@RestController
@EnableAutoConfiguration
public class CustomPortController implements EmbeddedServletContainerCustomizer {
/**
* 自定义端口
* @param container
*/
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setPort(8888);
}
@RequestMapping("/")
public String setPort(){
return "自定义端口:8888";
}
public static void main(String[] args) {
SpringApplication.run(CustomPortController.class,args);
}
}