Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml
程序员文章站
2022-03-04 18:19:27
...
示例
@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