精通SpringBoot——第二篇:视图解析器,静态资源和区域配置

今天让我们来看看另一个重要的类:WebMvcAutoConfigurationAdapter。先来看看它的声明:

@Configuration
@Import(EnableWebMvcConfiguration.class)
@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ResourceLoaderAware {

很显然,它也是SpringBoot的一个配置类,@Improt注解是被用来整合所有在@Configuration注解中定义的bean配置。这其实很像我们将多个XML配置文件导入到单个文件的情形。@Import注解实现了相同的功能。
再往下看可以看到SpringBoot中常见的viewResolver

    @Bean
        @ConditionalOnMissingBean
        public InternalResourceViewResolver defaultViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix(this.mvcProperties.getView().getPrefix());
            resolver.setSuffix(this.mvcProperties.getView().getSuffix());
            return resolver;
        }

        @Bean
        @ConditionalOnBean(View.class)
        @ConditionalOnMissingBean
        public BeanNameViewResolver beanNameViewResolver() {
            BeanNameViewResolver resolver = new BeanNameViewResolver();
            resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
            return resolver;
        }

        @Bean
        @ConditionalOnBean(ViewResolver.class)
        @ConditionalOnMissingBean(name = "viewResolver", value = ContentNegotiatingViewResolver.class)
        public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
            ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
            resolver.setContentNegotiationManager(
                    beanFactory.getBean(ContentNegotiationManager.class));
            // ContentNegotiatingViewResolver uses all the other view resolvers to locate
            // a view so it should have a high precedence
            resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
            return resolver;
        }

接着往下看,可以看到这个是配置区域的。@ConditionalOnProperty表示如果在application.properties中配置了spring.mvc.locale属性,则该配置会生效。

    @Bean
        @ConditionalOnMissingBean
        @ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
        public LocaleResolver localeResolver() {
            if (this.mvcProperties
                    .getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
                return new FixedLocaleResolver(this.mvcProperties.getLocale());
            }
            AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
            localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
            return localeResolver;
        }

再往下看是配置静态资源(包括/webjars/**,classpath:/META-INF/resources/webjars/")和favicon(可以通过在application.properties中设置spring.mvc.favicon.enabled来启用或禁用)

好了,文章到这里就结束了,静态资源这一块并没有什么特别的地方。我们需要理解的是这几个注解的用法,还有使用了配置属性,可以允许用户对其进行自定义。还有一个值得提一下,默认的地域解析器只会处理一个地域,通过上面提到的spring.mvc.locale来配置。

上一篇:新网域名查询和注册API接口类 源码


下一篇:什么是高防服务器?如何搭建DDOS流量攻击防护系统