liveBook · Manning

@crossorigin

As explained in Spring in Action, Sixth Edition

@CrossOrigin is a Spring annotation that configures cross-origin resource sharing for a controller or handler method.

@CrossOrigin configures cross-origin resource sharing (CORS) so a browser-based client served from another host or port can consume a Spring API. section 7.1.1

Listing 7.1 A RESTful controller for taco design API requests
package tacos.web.api;
 
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import tacos.Taco;
import tacos.data.TacoRepository;
 
@RestController
@RequestMapping(path="/api/tacos",                #1
                produces="application/json")
@CrossOrigin(origins="http://tacocloud:8080")     #2
public class TacoController {
  private TacoRepository tacoRepo;
 
  public TacoController(TacoRepository tacoRepo) {
    this.tacoRepo = tacoRepo;
  }
 
  @GetMapping(params="recent")
  public Iterable<Taco> recentTacos() {           #3
    PageRequest page = PageRequest.of(
            0, 12, Sort.by("createdAt").descending());
    return tacoRepo.findAll(page).getContent();
  }
}

See the complete TacoController example, where @CrossOrigin is placed on a REST controller alongside its API path and JSON response configuration. section 7.1.1

Allowing a separate frontend

A Taco Cloud API can allow a client at http://tacocloud:8080 by declaring @CrossOrigin(origins="http://tacocloud:8080") above TacoController. Multiple origins can be supplied as an array, such as http://tacocloud:8080 and http://tacocloud.com. section 7.1.1

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains the browser restriction and origin declaration, but does not detail CORS header mechanics or broader configuration.
Examples
Uses TacoController with one permitted origin, then expands the declaration to two origins.
What it assumes
Assumes a Spring REST controller and explains from the browser restriction why a separate frontend origin needs CORS.
What you can do after
Configure a Spring REST controller to accept browser requests from explicitly named origins.
How it connects
Connects REST controllers, JavaScript clients, browsers, and cross-origin resource sharing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.