Web 容器配置

spring boot 可以配置不同的容器官方支持 Tomcat, Jetty, Undertow。使用 EmbeddedServletContainerFactory, EmbeddedServletContainer 也可以自定义容器比如 AliTomcat, 以下按 tomcat 来举例

Servlets, Filters, Listeners

在传统项目中通常会定义很不同的 servlet 来进行动静分离,定义Filter来进行日志记录,定义Listeners来跟踪Request, Session生命周期。Spring boot 同样也支持.

@Configuration
public class CustomMvcConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(CustomMvcConfig.class);

    @Bean
    ServletRegistrationBean registrationBean() {
        // 静态文件servlet
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.addUrlMappings("/static/*");
        bean.setServlet(new DefaultServlet());
        return bean;
    }

    @Bean
    FilterRegistrationBean filterRegistrationBean() {
        // cros 配置 (生产环境切勿这样使用)
        FilterRegistrationBean bean = new FilterRegistrationBean();
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        List<String> allowedOrigins = new ArrayList<>();
        allowedOrigins.add(CorsConfiguration.ALL);
        corsConfiguration.setAllowedOrigins(allowedOrigins);

        corsConfiguration.setMaxAge(3600L);

        List<String> allowedMethods = new ArrayList<>();
        allowedMethods.add(CorsConfiguration.ALL);
        corsConfiguration.setAllowedMethods(allowedMethods);

        List<String> allowedHeaders = new ArrayList<>();
        allowedHeaders.add(CorsConfiguration.ALL);

        corsConfiguration.setAllowedHeaders(allowedHeaders);

        CorsFilter corsFilter = new CorsFilter(request -> corsConfiguration);

        corsFilter.setCorsProcessor(new DefaultCorsProcessor());

        bean.setFilter(corsFilter);

        return bean;
    }

    @Bean
    ServletListenerRegistrationBean<HttpSessionListener> servletListenerRegistrationBean() {
        // session 创建,销毁监听器
        ServletListenerRegistrationBean<HttpSessionListener> bean = new ServletListenerRegistrationBean<>();
        bean.setListener(new HttpSessionListener() {
            @Override
            public void sessionCreated(HttpSessionEvent se) {
                LOGGER.debug("create session");
            }

            @Override
            public void sessionDestroyed(HttpSessionEvent se) {
                LOGGER.debug("destroyed session");
            }
        });

        return bean;
    }

}

端口和地址绑定

  1. 使用application.properties 文件中 的server.port``server.address配置
  2. 编程配置

    @Component
    public class CustomizationBean implements EmbeddedServletContainerCustomizer {
    
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.setPort(9000);
        }
    
    }

    或者

    @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;
    }

Session

Http 压缩

跨域配置

  1. 使用 Spring 注解 @CrossOrigin 来进行直观细粒度的管理
  2. 使用 Filter 参见前面
  3. 使用全局配置

    @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/api/**")
                            .allowedOrigins("http://domain2.com")
                            .allowedMethods("PUT", "DELETE")
                            .allowedHeaders("header1", "header2", "header3")
                            .exposedHeaders("header1", "header2")
                            .allowCredentials(false).maxAge(3600);
                }
            };
        }

Json 配置

  1. 使用 Jackson2ObjectMapperBuilder

        @Bean
        public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
            Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
            builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
            builder.serializationInclusion(JsonInclude.Include.NON_EMPTY);
            builder.failOnUnknownProperties(false);
            return builder;
        }
  2. 直接使用 MappingJackson2HttpMessageConverter

    留给读者自己去实现

模板引擎

热加载

异常处理

连接池配置

新手使用 spring boot 很容易忽视这点注意以下参数

server.tomcat.max-connections= # Maximum number of connections that the server will accept and process at any given time.
server.tomcat.max-http-post-size=0 # Maximum size in bytes of the HTTP post content.
server.tomcat.max-threads=0 # Maximum amount of worker threads.
server.tomcat.min-spare-threads=0 # Minimum amount of worker threads

总结

  1. 大部分的配置都可以使用 application.properties (.yaml) 来配置
  2. 可以继承或者实现某个 bean 来替换默认的配置
  3. 可以完全使用自定义的 container 或者 WebMvcConfigurer 来实现
  4. spring boot 也完全支持使用 xml 的方式来配置,但是不推荐
  5. spring boot 只是做了一点方便的封装,xml 老手不要被吓到了。
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐