背景
系统之前为一个单页应用提供过Rest接口,部署时这个单页应用与系统不在同一域内,出现跨域无法访问的问题。Spring 从 4.2 版本开始提供了@CrossOrigin注解,让这个问题的解决变得非常简单。
实现一
首先看下@CrossOrigin的源码(删掉了开头的部分注释):
package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.web.cors.CorsConfiguration;
/**
* @author Russell Allen
* @author Sebastien Deleuze
* @author Sam Brannen
* @since 4.2
*/
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
/**
* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}
*/
@Deprecated
String[] DEFAULT_ORIGINS = { "*" };
/**
* @deprecated as of Spring 4.3.4, in favor of using {@link CorsConfiguration#applyPermitDefaultValues}
*/
@Deprecated
String[] DEFAULT_ALLOWED_HEADERS = { "*" };
/**
* @deprecated as of Spring 4