欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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:
Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml
跟 WebMvcConfigurationSupport:
注入了一些 HandlerMapping,这里面还设置了拦截器
Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml

跟 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();
}

Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml
Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml
跟 addInterceptors:
类 WebMvcConfigurerComposite 实现了示例中实现的 WebMvcConfigurer
Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml
跟 addInterceptors:
类 WebMvcConfigurer
Spring5 源码阅读笔记(5)基于注解的方法替换 spring-dispatcher.xml

相关标签: # MVC