多语言展示
当前在线:1477今日阅读:155今日分享:35

spring boot如何配置视图解析器

springboot的简单实使用
方法/步骤
1

spring是否自动装配了视图解析器ViewResolver,答案是肯定的,但是也需要你写配置文件。配置前缀后缀,和之前使用spring配置文件是一样的,只是简化了xml的配置,只需要两行即可解决配置。

2

首先看下springboot中WebMvcAutoConfiguration,mvc的自动装配配置文件。找到定义的视图解析器,defaultViewResolver。

3

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

4

可以看到引入的配置文件mvcProperties,这里源码查看mvcProperties,发现引入的WebMvcProperties。继续查看源码。 @ConfigurationProperties(     prefix = 'spring.mvc' ) public class WebMvcProperties {private final WebMvcProperties.View view;**************}注意配置注解,在配置文件中读取spring.mvc前缀的配置文件,这里不介绍ConfigurationProperties的使用了。

5

继续查看源码发现:public static class View {     private String prefix;     private String suffix;     public View() {       public String getPrefix() {         return this.prefix;     }

6

public void setPrefix(String prefix) {        this.prefix = prefix;    }    public String getSuffix() {        return this.suffix;    }    public void setSuffix(String suffix) {        this.suffix = suffix;    } }

7

源码查看到这里可以发现springboot对视图的封装,我们只需要在配置文件properties中配置,或者yaml文件配置ViewResolver的前缀和后缀即可。例子properties配置,yaml配置自行查看文档:spring.mvc.view.prefix=/views/ spring.mvc.view.suffix=.jsp

注意事项

yaml配置文件注意空格的使用

推荐信息