SpringBoot 官方文档示例:(56)通过WebMvcConfigurer来配置跨域

可以通过WebMvcConfigurer来配置跨域的请求

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration(proxyBeanMethods = false)
public class MyCorsConfiguration {
  @Bean
  public WebMvcConfigurer corsConfigurer() {
  return new WebMvcConfigurer() {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/api/**");
  }
  };
  }
}

其中addCorsMappings方法中的
registry.addMapping语句用来添加用来跨域的请求地址,本例表示以/api/开头的请求地址都可以跨域

CorsRegistry的源码:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.web.servlet.config.annotation;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.util.CollectionUtils;
import org.springframework.web.cors.CorsConfiguration;

public class CorsRegistry {
    private final List registrations = new ArrayList();

    public CorsRegistry() {
    }

    public CorsRegistration addMapping(String pathPattern) {
        CorsRegistration registration = new CorsRegistration(pathPattern);
        this.registrations.add(registration);
        return registration;
    }

    protected Map getCorsConfigurations() {
        Map configs = CollectionUtils.newLinkedHashMap(this.registrations.size());
        Iterator var2 = this.registrations.iterator();

        while(var2.hasNext()) {
            CorsRegistration registration = (CorsRegistration)var2.next();
            configs.put(registration.getPathPattern(), registration.getCorsConfiguration());
        }

        return configs;
    }
}

可见,所有跨域的请求映射是被保存到了一个ArrayList中了

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)