Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml

示例

@Configuration
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {

    @Autowired
    private UserInterceptor userInterceptor;

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(userInterceptor).addPathPatterns("/user/**").excludePathPatterns("/user/query/**");
        registry.addInterceptor(new UserInterceptor1()).addPathPatterns("/user/**").excludePathPatterns("");
        addInterceptors(registry);
    }
}

@EnableWebMvc 干了什么?

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

跟 DelegatingWebMvcConfiguration:
在这里插入图片描述
跟 WebMvcConfigurationSupport:
注入了一些 HandlerMapping,这里面还设置了拦截器
在这里插入图片描述

跟 getInterceptors:

protected final Object[] getInterceptors() {
	if (this.interceptors == null) {
		InterceptorRegistry registry = new InterceptorRegistry();
		//模板方法,见示例
		addInterceptors(registry);
		registry.addInterceptor(new ConversionServiceExposingInterceptor(mvcConversionService()));
		registry.addInterceptor(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider()));
		this.interceptors = registry.getInterceptors();
	}
	return this.interceptors.toArray();
}

在这里插入图片描述
在这里插入图片描述
跟 addInterceptors:
类 WebMvcConfigurerComposite 实现了示例中实现的 WebMvcConfigurer
在这里插入图片描述
跟 addInterceptors:
类 WebMvcConfigurer
在这里插入图片描述

发布了185 篇原创文章 · 获赞 271 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44367006/article/details/104940140