栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot——原生组件注入

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot——原生组件注入

目录

1、使用

1.使用Servlet API

2、使用RegistrationBean,

2、源码解析 

1、DispatcherServlet如何注册进来

2、优先匹配原则

1、使用

1.使用Servlet API

主启动类写ServletComponentScan注解

Servlet类写@WebServlet(@WebFilter、@WebListener)注解

注意:

直接响应,没有经过Spring的拦截器

2、使用RegistrationBean,

ServletRegistrationBean、FilterRegistrationBean、ServletListenerRegistrationBean

准备好MyServlet、MyFilter、MyServletContextListener类,无需在其上写注解。

编写MyRegistConfig类,如下图


// (proxyBeanMethods = true):保证依赖的组件始终是单实例的
@Configuration(proxyBeanMethods = true)
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);
    }
}

2、源码解析 

1、DispatcherServlet如何注册进来

容器中自动配置dispatcherServlet,属性绑定在WebMvcProperties中。

若要修改默认,在yml文件中写如下图: 

 通过DispatcherServletRegistrationBea把dispatcherServlet注册进来,如下图

而 DispatcherServletRegistrationBea继承自ServletRegistrationBean,如下下图

 

它的拦截路径由下列语句设置:

DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet, webMvcProperties.getServlet().getPath());

 其中,getPath最终在WebMvcProperties中设置,如下图

 默认映射的是/路径,若想修改dispatchServlrt的拦截路径,需要在yml文件中如下图设置

2、优先匹配原则

 DispatchServlet可以处理/路径的请求,但是如果容器中存在MyServlet可以处理更精准的/My请求。则/My请求交由MyServlet处理,并不走Spring的流程 

 

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/925034.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号