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类,如下图


/**
 * 1、MyServlet --> /my
 * 2、DispatcherServlet --> /
 */
// (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的流程 

 

 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值