java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot组件和容器

SpringBoot开发中的组件和容器详解

作者:韩_师兄

这篇文章主要介绍了SpringBoot开发中的组件和容器详解,SpringBoot 提供了一个内嵌的 Tomcat 容器作为默认的 Web 容器,同时还支持其他 Web 容器和应用服务器,需要的朋友可以参考下

Web原生组件

Web原生组件包括: Servlet、Filter、Listener等

相关使用

//  指定原生Servlet组件都放在那里
@ServletComponentScan(basePackages = "com.cf.admin")
// 效果:直接响应,没有经过Spring的拦截器
@WebServlet(urlPatterns = "/my")
@WebFilter(urlPatterns={"/css/*","/images/*"})
@WebListener

关于DispatchServlet 如何注册:

Tomcat-Servlet中 多个Servlet都能处理到同一层路径,精确优选原则

  • /my/
  • /my/1

RegistrationBean使用

ServletRegistrationBean , FilterRegistrationBean , and ServletListenerRegistrationBean

@Configuration
public class MyRegistConfig {
    @Bean
    public ServletRegistrationBean myServlet(){
        MyServlet myServlet = new MyServlet();
        return new ServletRegistrationBean(myServlet,"/my","/my02");
    }
    @Bean
    public FilterRegistrationBean myFilter(){
        MyFilter myFilter = new MyFilter();
//        return new FilterRegistrationBean(myFilter,myServlet());
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(myFilter);
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/my","/css/*"));
        return filterRegistrationBean;
    }
    @Bean
    public ServletListenerRegistrationBean myListener(){
        MySwervletContextListener mySwervletContextListener = new MySwervletContextListener();
        return new ServletListenerRegistrationBean(mySwervletContextListener);
    }
}

Servlet容器

切换Servlet

相关依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>

使用原理:

定制Servlet容器

1 实现 WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> 把配置文件的值和ServletWebServerFactory 进行绑定

2 修改配置文件servce.xxx, 直接自定义 ConfigurableServletWebServerFactory

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;
@Component
public class CustomizationBean implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {
    @Override
    public void customize(ConfigurableServletWebServerFactory server) {
        server.setPort(9000);
    }
}

到此这篇关于SpringBoot开发中的组件和容器详解的文章就介绍到这了,更多相关SpringBoot组件和容器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文