SpringBoot2.0中,配置嵌入式Servlet容器,EmbeddedServletContainerCustomizer 已经被
WebServerFactoryCustomizer代替,
1.第一种方式:修改配置文件
-
修改和server有关的配置 (ServerProperties)
server.port=8081 server.context-path=/crud server.tomcat.uri-encoding=UTF-8 //通用的Servlet容器设置 server.xxx //Tomcat的设置 server.tomcat.xxx
2.第二种方式:编写一个WebServerFactoryCustomizer
:嵌入式的Servlet容器的定制器;来修改Servlet容器的配置
查看源码:
(1)WebServerFactoryCustomizer是一个接口
@FunctionalInterface
public interface WebServerFactoryCustomizer<T extends WebServerFactory> {
/**
* Customize the specified {@link WebServerFactory}.
* @param factory the web server factory to customize
*/
void customize(T factory);
}
public interface WebServerFactory {
}
(2)Ctrl + Alt + B 查看 WebServerFactory的实现类:
(3)我们发现:
可以实现ConfigurableWebServerFactory 接口,并重写其中的方法;可以达到我们想要的效果
public interface ConfigurableWebServerFactory extends WebServerFactory, ErrorPageRegistry {
/**
* Sets the port that the web server should listen on. If not specified port '8080'
* will be used. Use port -1 to disable auto-start (i.e start the web application
* context but not have it listen to any port).
* @param port the port to set
*/
void setPort(int port);
/**
* Sets the specific network address that the server should bind to.
* @param address the address to set (defaults to {@code null})
*/
void setAddress(InetAddress address);
/**
* Sets the error pages that will be used when handling exceptions.
* @param errorPages the error pages
*/
void setErrorPages(Set<? extends ErrorPage> errorPages);
(4)在我们自定义的MyMvcConfig类,定义方法:
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() {
//定制嵌入式的servlet容器相关的规则
@Override
public void customize(ConfigurableWebServerFactory factory) {
factory.setPort(8083);
}
};
}
因此,针对如何修改SpringBoot的默认配置,我们有几种思想:
模式:
1)、SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean、@Component)如果有就用用户配置的,如果没有,才自动配置;如果有些组件可以有多个(ViewResolver)将用户配置的和自己默认的组合起来;
2)、在SpringBoot中会有非常多的xxxConfigurer帮助我们进行扩展配置
3)、在SpringBoot中会有很多的xxxCustomizer帮助我们进行定制配置