import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 跨域设置
* @see org.springframework.web.bind.annotation.CrossOrigin
*/
@Configuration
public class CorsConfigure {
@Value("${server.cors.pattern:/api/**}")
private String pathPattern;
@Bean
public WebMvcConfigurer corsConfigurer() {
LoggerFactory.getLogger(CorsConfigure.class).info("CORS enabled at `{}`, you can change it with property `server.cors.pattern` in application.yml.", pathPattern);
return new CorsWebMvcConfigurerAdapter(pathPattern);
}
private static class CorsWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
private final String pathPattern;
public CorsWebMvcConfigurerAdapter(String pathPattern) {
this.pathPattern = pathPattern;
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(pathPattern);
}
}
}
也可以加API上加注解
@CrossOrigin
网友评论