开发中,有的项目需要加入跨域配置,有的不需要,故采用注解加手动注册的方式,使项目可以自由继续跨域配置
自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Import(CorsFilterConfiguration.class)
public @interface EnableCorsFilter {
String path() default "/**";
boolean allowCredentials() default true;
String[] allowedOrigin() default "*";
String[] allowedHeader() default "*";
String[] allowedMethod() default "*";
long maxAge() default 3600L;
}
注册filter
public class CorsFilterConfiguration implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// 获取注解信息
AnnotationAttributes annotationAttributes =
AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableCorsFilter.class.getName(), false));
// 增加跨域配置
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(annotationAttributes.getBoolean("allowCredentials"));
String[] allowedOrigins = annotationAttributes.getStringArray("allowedOrigin");
for (String allowedOrigin : allowedOrigins) {
config.addAllowedOrigin(allowedOrigin);
}
String[] allowedHeaders = annotationAttributes.getStringArray("allowedHeader");
for (String allowedHeader : allowedHeaders) {
config.addAllowedHeader(allowedHeader);
}
String[] allowedMethods = annotationAttributes.getStringArray("allowedMethod");
for (String allowedMethod : allowedMethods) {
config.addAllowedMethod(allowedMethod);
}
config.setMaxAge(annotationAttributes.getNumber("maxAge"));
source.registerCorsConfiguration(annotationAttributes.getString("path"), config);
CorsFilter corsFilter = new CorsFilter(source);
// 注册
AbstractBeanDefinition beanDefinition =
BeanDefinitionBuilder.rootBeanDefinition(FilterRegistrationBean.class).addPropertyValue("filter",corsFilter).addPropertyValue("order", 0).getBeanDefinition();
registry.registerBeanDefinition("corsFilter", beanDefinition );
}
}