专栏首页软件开发-青出于蓝SpringFramework之ViewResolver优化

SpringFramework之ViewResolver优化

    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

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

@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

web-support.exclusive-view-resolver=defaultViewResolver,beanNameViewResolver

    List-2中

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

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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Springcloud之zuul的过滤头部

    Springcloud的版本是Greenwich.SR2,Springboot版本是2.1.6.release.

    克虏伯
  • Springsecurity之SecurityContextHolderStrategy

    注:下面分析的版本是spring-security-4.2.x,源码的github地址是: https://github.com/spring-projects...

    克虏伯
  • SpringFramework之RequestBodyAdvice的使用

    有人用RequestBodyAdvice来做参数的解密(前端传过来的是加密的),或者使用RequestBodyAdvice进行全局统一返回,但是我的需求是只对J...

    克虏伯
  • 2017-03-03学习笔记

    一、String StringBuffer.toString()源码: @Override public synchronized String toStrin...

    Zephery
  • java+内存分配及变量存储位置的区别

    Java内存分配与管理是Java的核心技术之一,之前我们曾介绍过Java的内存管理与内存泄露以及Java垃圾回收方面的知识,今天我们再次深入Java核心,详细...

    bear_fish
  • Java每日一练(2017/6/17)

    Java基础 | 数据库 | Android | 学习视频 | 学习资料下载 最新通知 ●回复"每日一练"获取以前的题目! ●【新】Ajax知识点视频更新了!(...

    Java学习
  • 物理刚体挖洞!另一种实现!

    在 物理挖洞-优化篇 和 物理挖洞-实现篇 中介绍了一种用多边形链条组件(cc.PhysicsChainCollider)实现物理挖洞的方法。这次打算用多边形碰...

    白玉无冰
  • Caused by: org.xml.sax.SAXParseException; systemId: file:/home/hadoop/hive-0.12.0/conf/hive-site.xml

    1:Hive安装的过程(Hive启动的时候报的错误),贴一下错误,和为什么错,以及解决方法: 1 [root@master bin]# ./hive 2 1...

    别先生
  • OpenAI开发的分级强化学习算法旨在解决高级操作

    我们已经开发了一种分层强化学习算法,它学习用于解决一组任务的高级操作,可以快速解决需要数千个时间步长的任务。我们的算法应用于一组导航问题时,会发现一组用于在不同...

    AiTechYun
  • 小白&JAP君|面向对象的三大特征你真的了解了吗?

    面向对象编程是如今最流行的编程思想,像JAVA,Python,C++...都是属于面向对象编程,今天给大家说说面向对象编程的三大特性,深刻理解这三...

    Python进击者

扫码关注云+社区

领取腾讯云代金券