Springboot中WebMvcConfigurer接口詳解


用途:跨域、攔截器、靜態資源處理

接口方法的作用:

    addInterceptors:攔截器
    addViewControllers:頁面跳轉
    addResourceHandlers:靜態資源
    configureDefaultServletHandling:默認靜態資源處理器
    configureViewResolvers:視圖解析器
    configureContentNegotiation:配置內容裁決的一些參數
    addCorsMappings:跨域
    configureMessageConverters:信息轉換器

   在Spring Boot 1.5版本都是靠重寫WebMvcConfigurerAdapter的方法來添加自定義攔截器,消息轉換器等。SpringBoot 2.0 后,該類被標記為@Deprecated(棄用)。官方推薦直接實現WebMvcConfigurer或者直接繼承WebMvcConfigurationSupport,方式一實現     WebMvcConfigurer接口(推薦),方式二繼承WebMvcConfigurationSupport類,具體實現可看這篇文章。https://blog.csdn.net/fmwind/article/details/82832758

package com.olive.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * WebMvcConfigurer
 *
 */
@Configuration
@EnableWebMvc
public class ConfigurerAdapter implements WebMvcConfigurer {

    //圖片保存路徑
    public static final String PIC_PATH = "/landscape/";
    @Value(value="${application.profile}")
    private  String  profile;
  @Autowired
  private AuthorityInterceptor authorityInterceptor;
//跨域 @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedHeaders("*") .allowedOrigins("*") .allowedMethods("GET","POST","PUT","DELETE"); } // 可解決Long 類型在 前端精度丟失的問題, 如不想全局 直接添加注解 @JsonSerialize(using= ToStringSerializer.class) 到相應的字段 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0); /** 圖片傳路徑 */ registry.addResourceHandler("/landscape/**").addResourceLocations("file:" + profile); }



  @Override
  public void addInterceptors(InterceptorRegistry registry{
    //注冊自己的攔截器並設置攔截的請求路徑
    registry.addInterceptor(authorityInterceptor).addPathPatterns("/**");
    super.addInterceptors(registry);
  }

}

 

 

參考文章:https://blog.csdn.net/kuishao1314aa/article/details/109777304


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM