Java --- springboot2查看配置是否生效

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Spring Boot应用中,如果你想要允许跨域请求并在周末(周六、周日)特定时间开启Access-Control-Allow-Origin策略,你可以创建一个自定义过滤器(Filter),例如使用`@CrossOrigin`注解,并通过`@PreAuthorize`或`@ConditionalOnDate`来控制其生效的时间。 首先,创建一个定制的过滤器,比如`WeekendCorsFilter.java`: ```java import org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; @Configuration @Component public class WeekendCorsFilter { private final ManagementServerProperties management; public WeekendCorsFilter(ManagementServerProperties management) { this.management = management; } @Bean(name = "weekendCorsFilter") public WebMvcConfigurer corsConfigurer() { return (configurer) -> { configurer.addCorsConfiguration( "/**", // 允许所有的路径 headers -> { if (isWeekend()) { // 检查是否为周末 headers.setAllowCredentials(true); // 设置允许凭证 headers.addAllowedHeader("*"); // 允许所有头信息 headers.addAllowedMethod("*"); // 允许所有HTTP方法 headers.addAllowedOrigin("*"); // 允许来自任何源的请求 } else { // 非周末则按默认设置或你自己的规则处理 configurer.cors().allowCredentials(false); configurer.cors().allowedOrigins("http://your-origin.com"); } }); }; } private boolean isWeekend() { String[] daysOfWeek = {"Saturday", "Sunday"}; for (String day : daysOfWeek) { if (management.getEndpointProperties().getWeb().getDatepatterns().contains(day)) { return true; // 如果找到对应的日期模式,则为周末 } } return false; } } ``` 然后在启动或Spring Boot Actuator配置中启用这个过滤器: ```java @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Autowired private WeekendCorsFilter weekendCorsFilter; // ... @PostConstruct public void init() { weekendCorsFilter.corsConfigurer(); // 加载配置 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸭鸭老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值