前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringFramework之ViewResolver优化

SpringFramework之ViewResolver优化

作者头像
克虏伯
发布2020-08-07 01:19:24
4680
发布2020-08-07 01:19:24
举报
文章被收录于专栏:软件开发-青出于蓝

    Springboot版本是2.x

    Springboot中,对mvc进行自动化配置时在WebMvcAutoConfiguration中会自动注入InternalResourceViewResolver(渲染jsp的)、BeanNameViewResolver、ContentNegotiatingViewResolver。

    但是我们一般是直接返回json或者使用thymeleaf,所以InternalResourceViewResolver和BeanNameViewResolver是用不到的,但是springmvc的render中这几个都会被调用到,所以如果我们将InternalResourceViewResolver和BeanNameViewResolver去掉,不加入到mvc的ViewResolver集合中那么就可以优化渲染的过程。

    来看ContentNegotiatingViewResolver#resolveViewName,如下List-1

List-1

代码语言:javascript
复制
public View resolveViewName(String viewName, Locale locale) throws Exception {
    RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
    Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
    List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
    if (requestedMediaTypes != null) {
        List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);
        View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);
        if (bestView != null) {
            return bestView;
        }
    }
    ...
}

...

private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes)
        throws Exception {

    List<View> candidateViews = new ArrayList<>();
    if (this.viewResolvers != null) {
        Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set");
        for (ViewResolver viewResolver : this.viewResolvers) {
            View view = viewResolver.resolveViewName(viewName, locale);
            if (view != null) {
                candidateViews.add(view);
            }
            for (MediaType requestedMediaType : requestedMediaTypes) {
                List<String> extensions = this.contentNegotiationManager.resolveFileExtensions(requestedMediaType);
                for (String extension : extensions) {
                    String viewNameWithExtension = viewName + '.' + extension;
                    view = viewResolver.resolveViewName(viewNameWithExtension, locale);
                    if (view != null) {
                        candidateViews.add(view);
                    }
                }
            }
        }
    }
    if (!CollectionUtils.isEmpty(this.defaultViews)) {
        candidateViews.addAll(this.defaultViews);
    }
    return candidateViews;
}

    List-1中resolveViewName方法中调用getCandidateViews获取候选View集合,getCandidateViews方法中循坏遍历viewResolvers,逐个拿到对应的View然后加入到结果集合中,我们可以debug下这个viewResolvers的值有InternalResourceViewResolver、BeanNameViewResolver、ThymeleafViewResolver、ContentNegotiatingViewResolver,所以默认情况下执行了很多无用的代码。

    我们怎么将viewResolvers的集合中将InternalResourceViewResolver、BeanNameViewResolver去掉呢?

    ContentNegotiatingViewResolver是WebMvcAutoConfiguration中自动注入进去的,是单例bean,那么我们可以在spring完成这个bean的创建、初始化等后来修改里面属性viewResolvers的值。

    我们需要知道spring上下文什么时候启动完成,回到AbstractApplicationContext#refresh(),上下文启动完成后调用finishRefresh(),进而调用publishEvent(new ContextRefreshedEvent(this)),即发布ContextRefreshedEvent事件,所以我们可以通过监听这个事件然后在spring上下文启动完成后对ContentNegotiatingViewResolver这个bean进行修改。

    创建ApplicationListener来监听ContextRefreshedEvent事件,如下List-2

List-2

代码语言:javascript
复制
@Component
public class ExclusiveViewResolverApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    private static final String EXCLUSIVE_VIEW_RESOLVER="web-support.exclusive-view-resolver";
    private static final Class<ViewResolver> VIEW_RESOLVER_CLASS = ViewResolver.class;
    private final String[] exclusiveViewResolverBeanNameList;

    public ExclusiveViewResolverApplicationListener(@Value("${" + EXCLUSIVE_VIEW_RESOLVER+ "}") String exclusiveViewResolverBeanName) {
        this.exclusiveViewResolverBeanNameList = exclusiveViewResolverBeanName.split(",");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        this.configureExclusiveViewResolver(applicationContext);
    }

    private void configureExclusiveViewResolver(ApplicationContext applicationContext) {
        Map<String, ViewResolver> viewResolversMap = BeanFactoryUtils
                .beansOfTypeIncludingAncestors(applicationContext, VIEW_RESOLVER_CLASS);
        int size = viewResolversMap.size();
        if (size >= 2) {
            for (String exclusiveViewResolverName: exclusiveViewResolverBeanNameList) {
                ViewResolver exclusiveViewResolver = viewResolversMap.remove(exclusiveViewResolverName);
                if (exclusiveViewResolver == null) {
                    throw new NoSuchBeanDefinitionException(VIEW_RESOLVER_CLASS,exclusiveViewResolverName);
                }
            }
            List<ViewResolver> viewResolvers = new ArrayList<>(viewResolversMap.values());
            //要把ContentNegotiatingViewResolver排除,不然会递归调用导致栈溢出
            viewResolvers.removeIf(viewResolver -> viewResolver instanceof ContentNegotiatingViewResolver);
            ContentNegotiatingViewResolver contentNegotiatingViewResolver = applicationContext.getBean(ContentNegotiatingViewResolver.class);
            contentNegotiatingViewResolver.setViewResolvers(viewResolvers);
        }
    }
}

    然后在application.properties中配置,如List-3,这里的defaultViewResolver和beanNameViewResolver是固定的,不能修改,因为这是InternalResourceViewResolver和BeanNameViewResolver的bean name——怎么知道的呢,从WebMvcAutoConfiguration中知道,这个bean name是方法名称。

List-3

代码语言:javascript
复制
web-support.exclusive-view-resolver=defaultViewResolver,beanNameViewResolver

    List-2中

  1. 收到spring上下文启动完成的事件后,从ApplicationContext中获取所有ViewResolver实例,移除我们配置的defaultViewResolver和beanNameViewResolver
  2. 从applicationContext中获取ContentNegotiatingViewResolver实例,之后将过滤后的viewResolver设置给其属性

    这样,回到List-1中,去获取候选View的时候,遍历的viewResolver就只有ThymeleafViewResolver了。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档