41 lines
1.2 KiB
Java
41 lines
1.2 KiB
Java
|
|
package com.example.oss.config;
|
|||
|
|
|
|||
|
|
import com.example.oss.util.OssUtils;
|
|||
|
|
import lombok.RequiredArgsConstructor;
|
|||
|
|
import lombok.extern.slf4j.Slf4j;
|
|||
|
|
import org.springframework.boot.ApplicationArguments;
|
|||
|
|
import org.springframework.boot.ApplicationRunner;
|
|||
|
|
import org.springframework.core.annotation.Order;
|
|||
|
|
import org.springframework.stereotype.Component;
|
|||
|
|
|
|||
|
|
/**
|
|||
|
|
* OSS Bucket CORS 初始化
|
|||
|
|
* <p>
|
|||
|
|
* 应用启动时自动配置 OSS 跨域规则,解决前端直传跨域问题。
|
|||
|
|
* 需在配置中开启:aliyun.oss.cors-enabled=true
|
|||
|
|
* </p>
|
|||
|
|
*
|
|||
|
|
* <h3>工作原理:</h3>
|
|||
|
|
* <ol>
|
|||
|
|
* <li>Spring Boot 启动完成后自动执行</li>
|
|||
|
|
* <li>读取 aliyun.oss.cors-enabled 配置</li>
|
|||
|
|
* <li>如果开启,调用 OSS API 设置 Bucket 的 CORS 规则</li>
|
|||
|
|
* <li>如果失败(如权限不足),仅打印警告,不影响应用启动</li>
|
|||
|
|
* </ol>
|
|||
|
|
*
|
|||
|
|
* <p>也可以不使用此自动配置,改为在阿里云控制台手动设置 CORS。</p>
|
|||
|
|
*/
|
|||
|
|
@Slf4j
|
|||
|
|
@Component
|
|||
|
|
@Order(100) // 较晚执行,确保其他组件已就绪
|
|||
|
|
@RequiredArgsConstructor
|
|||
|
|
public class OssCorsInitRunner implements ApplicationRunner {
|
|||
|
|
|
|||
|
|
private final OssUtils ossUtils;
|
|||
|
|
|
|||
|
|
@Override
|
|||
|
|
public void run(ApplicationArguments args) {
|
|||
|
|
ossUtils.configureBucketCors();
|
|||
|
|
}
|
|||
|
|
}
|