knife4j静态资源
时间: 2025-06-04 07:26:23 浏览: 28
### Knife4j 静态资源使用说明及配置教程
Knife4j 是 Swagger 的增强工具,提供了更丰富的功能和更友好的用户体验。在实际项目中,静态资源的正确加载对于文档展示至关重要。以下是关于 Knife4j 静态资源的相关信息及配置方法:
#### 1. 引入依赖
在使用 Knife4j 之前,需要确保项目中已正确引入相关依赖。根据引用内容[^2],可以使用以下 Maven 依赖:
```xml
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
```
#### 2. 配置静态资源路径
Knife4j 默认会加载静态资源文件(如 CSS、JS 等),但有时需要手动配置以确保资源能够正确加载。在 `application.yml` 或 `application.properties` 文件中添加以下配置[^3]:
```yaml
knife4j:
enable: true
swagger:
ui:
enabled: true
```
此外,如果项目中存在自定义静态资源路径,可以通过以下方式配置 Spring Boot 的静态资源映射规则:
```yaml
spring:
mvc:
static-path-pattern: /static/**
```
#### 3. 解决静态资源加载问题
在某些情况下,静态资源可能无法正确加载,例如项目中启用了统一异常处理或自定义拦截器。此时需要对 WebMvc 配置进行调整[^3]。创建一个配置类并添加以下代码:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 添加静态资源路径映射
registry.addResourceHandler("/swagger-ui/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
```
#### 4. 访问静态资源
完成上述配置后,可以通过以下 URL 访问 Knife4j 提供的接口文档页面:
- `http://localhost:8080/doc.html`[^1]
- `http://localhost:8080/swagger-ui/index.html`[^4]
#### 5. 注意事项
- 如果项目中使用了 Spring Security,需确保为 `/doc.html` 和 `/swagger-ui/**` 路径放行访问权限。
- 在生产环境中,建议禁用 Knife4j 或将其访问权限限制为内部开发人员专用。
---
### 示例代码:Spring Security 放行配置
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/doc.html", "/swagger-ui/**", "/webjars/**").permitAll() // 放行 Knife4j 资源
.anyRequest().authenticated();
}
}
```
---
阅读全文
相关推荐


















