spring是否自动装配了视图解析器ViewResolver,答案是肯定的,但是也需要你写配置文件。配置前缀后缀,和之前使用spring配置文件是一样的,只是简化了xml的配置,只需要两行即可解决配置。
首先看下springboot中WebMvcAutoConfiguration,mvc的自动装配配置文件。找到定义的视图解析器,defaultViewResolver。
@Bean @ConditionalOnMissingBean public InternalResourceViewResolver defaultViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix(this.mvcProperties.getView().getPrefix()); resolver.setSuffix(this.mvcProperties.getView().getSuffix()); return resolver; }
可以看到引入的配置文件mvcProperties,这里源码查看mvcProperties,发现引入的WebMvcProperties。继续查看源码。 @ConfigurationProperties( prefix = 'spring.mvc' ) public class WebMvcProperties {private final WebMvcProperties.View view;**************}注意配置注解,在配置文件中读取spring.mvc前缀的配置文件,这里不介绍ConfigurationProperties的使用了。
继续查看源码发现:public static class View { private String prefix; private String suffix; public View() { public String getPrefix() { return this.prefix; }
public void setPrefix(String prefix) { this.prefix = prefix; } public String getSuffix() { return this.suffix; } public void setSuffix(String suffix) { this.suffix = suffix; } }
源码查看到这里可以发现springboot对视图的封装,我们只需要在配置文件properties中配置,或者yaml文件配置ViewResolver的前缀和后缀即可。例子properties配置,yaml配置自行查看文档:spring.mvc.view.prefix=/views/ spring.mvc.view.suffix=.jsp
yaml配置文件注意空格的使用