概述
Spring Boot中扩展SpringMVC的功能
之前可以通过创建xml配置文件进行SpringMVC的扩展:springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:view-controller path="/hello" view-name="success" />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
现在我们通过编写一个配置类(@Configuration),既保留所有的自动配置,也能用我们扩展的配置。
-
在spring boot1.0+,我们可以使用WebMvcConfigurerAdapter来扩展springMVC的功能,其中自定义的拦截器并不会拦截静态资源(js、css等)。
-
在Spring Boot2.0版本中,WebMvcConfigurerAdapter这个类被弃用了。
-
扩展关于MVC的配置:
-
1、继承WebMvcConfigurationSupport:继承WebMvcConfigurationSupport之后,
-
可以使用这些add…方法添加自定义的拦截器、试图解析器等等这些组件。
-
2、实现WebMvcConfigurer接口:Spring Boot2.0是基于Java8的,
-
Java8有个重大的改变就是接口中可以有default方法,而default方法是不需要强制实现的。
-
上述的WebMvcConfigurerAdapter类就是实现了WebMvcConfigurer这个接口,所以我们不需要继承WebMvcConfigurerAdapter类,可以直接实现WebMvcConfigurer接口,用法与继承这个适配类是一样的。
-
两种方法都可以作为WebMVC的扩展,去自定义配置。
-
**区别就是:**继承WebMvcConfigurationSupport会使Spring Boot关于WebMVC的自动配置失效,需要自己去实现全部关于WebMVC的配置;
-
而实现WebMvcConfigurer接口的话,Spring Boot的自动配置不会失效,可以有选择的实现关于WebMVC的配置。
package com.cyl.restcrud.config;
/**
* @author cuiyongling
* @since V1.0.0
* 2020-11-13 15:38
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//@EnableWebMvc //接管SpringMVC,不推荐使用
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/success").setViewName("success");
}
/**
* 所有的WebMvcConfigurer组件都会在一起使用
* @return
*/
@Bean // 将组件注册在容器中
public WebMvcConfigurer webMvcConfigurer(){
WebMvcConfigurer wmc = new WebMvcConfigurer() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
}
};
return wmc;
}
}
最后
以上就是碧蓝羊为你收集整理的Spring Boot中扩展SpringMVC的功能的全部内容,希望文章能够帮你解决Spring Boot中扩展SpringMVC的功能所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复