有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java动态地从数据库中检索控制器中特定方法的Spring Boot CORS配置

我正在尝试使用

@CrossOrigin on Controller and Handler Method

public class AccountController {

@CrossOrigin("retreive data from DB")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
    // ...
}

}

我试过使用下面的方法,但它只在spring启动时设置,并且只在下次重新启动服务时进行更改

@Bean
public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
   // CorsConfiguration config = jHipsterProperties.getCors();

       CorsConfiguration config=CorsService.fetchCorsConfigFromDb;
    if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
        log.debug("Registering CORS filter");
        source.registerCorsConfiguration("/api/**", config);
        source.registerCorsConfiguration("/management/**", config);
        source.registerCorsConfiguration("/v2/api-docs", config);
    }
    return new CorsFilter(source);
}

fetchCorsConfigFromDb will fetch data from DB. Any changes from DB will be reflected only when Spring Boot App is restarted...


共 (1) 个答案

  1. # 1 楼答案

    用于CorsService.fetchCorsConfigFromDb; 它应该从缓存加载

    然后,您可以在运行时更新缓存

    你应该实现CorsService.fetchCorsConfig();

    1. 此方法应首先在缓存中查找任何cors配置,如果发现任何配置,请直接从缓存加载,否则您将从数据库中检索cors并更新缓存
    2. 创建运行时更新cors方法CorsService.updateCorsConfig();,这将在数据库中更新cors,然后更新缓存