五、Spring MVC

https://www.bilibili.com/video/BV1gW411W76m?p=1

SpringBoot自动配置好了SpringMVC

自动配置了ViewResolver(视图解析器:根据方法的返回值得到视图对象(View),视图对象决定如何渲染)

ContentNegotiatingViewResolver:组合所有的视图解析器

如何定制:我们可以自己给容器中添加师徒解析器;自动将其组合

package com.dreamtech.webrestfulcrud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

import java.util.Locale;

@SpringBootApplication
public class WebRestfulCrudApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebRestfulCrudApplication.class, args);
    }

    @Bean
    public ViewResolver myview(){
        return new MyViewResolver();
    }

    private static class MyViewResolver implements ViewResolver{

        @Override
        public View resolveViewName(String s, Locale locale) throws Exception {
            return null;
        }
    }
}

如何修改springboot的默认配置

模式:1)SpringBoot在自动配置很多组件的时候,先看容器中有没有用户自己配置的(@Bean,@Component)如果有就用用户配置的,如果没有才自动配置;如果有些组件可以有多个,将用户配置的与自己默认的组合起来。

2.扩展SpringMVC

编写一个配置类(@Configuration),是WebMVCConfigurerAdapter类型,不能标注@EnableWebMVC

package com.dreamtech.webrestfulcrud.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


//使用其扩展SpringMVC功能
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {

    public void addViewController(ViewControllerRegistry registry){
        //浏览器发送请求也来页面
        registry.addViewController("/hello").setViewName("success");
    }

}

在Spring 5.0 中,已经将 WebMvcConfigurerAdapter 抽象类加上 @Deprecated 注解 记为过时,我们看到,WebMvcConfigurerAdapter  抽象类实现了 WebMvcConfigurer 接口,这里我们只需要将 extends WebMvcConfigurerAdapter  替换为 implements WebMvcConfigurer 即可。

https://blog.csdn.net/qq_38164123/article/details/80392904

原理

1)WebMvcConfigurerAdapter 是SpringMVCde自动配置类

2)在做其他自动配置时会导入EnableWebMVCConfiguration.class

3)容器中所有的配置一起起作用,我们的配置类也会被调用 

3.全面接管SpringMVC(不推荐)

SpringBoot对SpringMVC的自动配置不需要了,所有都是自己配;所有web场景自动配置都失效

添加@EnableWebMVC即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值