在Spring Boot中使用@CrossOrigin

Jon*_*nik 3 spring spring-mvc cors spring-boot

我正在使用最新的Spring Boot(1.2.7.RELEASE).我想使用@CrossOrigin包中的注释,org.springframework.web.bind.annotation如Spring文档中的CORS支持部分所述.

我认为我已经拥有了所有必需的依赖项(通过Spring Boot默认值),但这很令人困惑:CrossOrigin找不到,即使RestController来自同一个包的东西也能正常工作!

在此输入图像描述

Error:(8, 47) java: cannot find symbol
  symbol:   class CrossOrigin
  location: package org.springframework.web.bind.annotation
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?已CrossOrigin被从Spring MVC的更高版本删除,还是我失去了一些依赖?

pom.xml中:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.7.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)

Jon*_*nik 5

好吧,看起来像最新的Spring Boot版本,1.2.7.RELEASE目前还太老了,不能有一个版本的Spring MVC CrossOrigin.(Spring Boot 1.2.7使用Spring版本4.1.8).

我更新到最新的Spring Boot 1.3发布候选版(1.3.0.RC1),它可以工作:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.0.RC1</version>
</parent>
Run Code Online (Sandbox Code Playgroud)

还需要指定spring-milestones存储库pom.xml以便能够使用非发布版本.

<repositories>
    <repository>
        <id>spring-milestones</id>
        <url>http://repo.spring.io/milestone</url>
    </repository>
</repositories>
Run Code Online (Sandbox Code Playgroud)

更新:覆盖Spring版本

正如StéphaneNic​​oll指出的那样,使用Spring 4.2.2类(例如CrossOrigin)的一种更简单的方法是:

<properties> 
    <!-- ... -->
    <spring.version>4.2.2.RELEASE</spring.version>
</properties>
Run Code Online (Sandbox Code Playgroud)

  • <性能> <spring.version> 4.2.2.RELEASE </spring.version> </属性> (3认同)
  • 如果你想要的话,可以使用Spring Framework`1.2.7`和Spring Framework`4.2.2.RELEASE`.转发覆盖不是问题.迁移到1.3时,请确保删除覆盖 (2认同)