programing

swagger-ui.html 기본 경로 변경 방법

sourcejob 2023. 7. 18. 21:42
반응형

swagger-ui.html 기본 경로 변경 방법

는 내 스웨거-의 길을 바꾸고 싶습니다.localhost:8080/swagger-ui.html로.localhost:8080/myapi/swagger-ui.htmlspringboot리다이렉트는 나에게 무력합니다.

Spring Boot의 application.properties에서

springdoc.swagger-ui.path=/swagger-ui-custom.html

당신의 경우에는 그럴 것입니다.

springdoc.swagger-ui.path=/myapi/swagger-ui.html

어떤 이유로 리디렉션하지 않으려는 경우/swagger-ui.html컨텐츠를 홈 보기로 설정하여 resources/static/index.dll에서 index.dll을 설정할 수 있습니다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to another awesome Microservice</title>
</head>
<body>
    <script>
        document.body.innerHTML = '<object type="text/html" data="/swagger-ui.html" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px"></object>';
    </script>
</body>
</html>

그런 다음 http://localhost:8080/에 액세스하면 스웨거 문서가 표시됩니다.

마지막으로 다음을 사용하여 경로 및 .vmdk 파일을 사용자 지정할 수 있습니다.

registry.addViewController("/swagger").setViewName("forward:/index.html");

대답을 암시하는 것처럼.

application.properties에서 springfox 속성을 수정할 수 있습니다.

예를 들어, 기본 URL을 편집하려면 다음과 같이 하십시오.

springfox.documentation.swagger-ui.base-url=documentation

예를 들어 다음으로 설정합니다./documentation을 호되게 꾸짖을 것입니다./documentation/swagger-ui/index.html

예를 들어, 다음과 같이 추가합니다.documentationprefix - 경로에 대해 이렇게 할 수 있습니다.http://localhost:8080/documentation/swagger-ui.html:

코틀린

@Configuration
@EnableSwagger2
@ConfigurationPropertiesScan("your.package.config")
@Import(value = [BeanValidatorPluginsConfiguration::class])
class SwaggerConfiguration(
    private val swaggerContactProp: SwaggerContactProp, private val swaggerProp: SwaggerProp
) : WebMvcConfigurationSupport() {

    // https://springfox.github.io/springfox/docs/current/
    @Bean
    fun api(): Docket = Docket(DocumentationType.SWAGGER_2)
        .groupName("Cards")
        .apiInfo(getApiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("your.controllers.folder"))
        .paths(PathSelectors.any())
        .build()

    private fun getApiInfo(): ApiInfo {
        val contact = Contact(swaggerContactProp.name, swaggerContactProp.url, swaggerContactProp.mail)
        return ApiInfoBuilder()
            .title(swaggerProp.title)
            .description(swaggerProp.description)
            .version(swaggerProp.version)
            .contact(contact)
            .build()
    }

    override fun addViewControllers(registry: ViewControllerRegistry) {
        with(registry) {
            addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs").setKeepQueryParams(true)
            addRedirectViewController(
                "/documentation/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui"
            )
            addRedirectViewController(
                "/documentation/swagger-resources/configuration/security", "/swagger-resources/configuration/security"
            )
            addRedirectViewController("/documentation/swagger-resources", "/swagger-resources")
        }
    }

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        registry.addResourceHandler("/documentation/**").addResourceLocations("classpath:/META-INF/resources/")
    }
}

@ConfigurationProperties(prefix = "swagger")
@ConstructorBinding
data class SwaggerProp(val title: String, val description: String, val version: String)

@ConfigurationProperties(prefix = "swagger.contact")
@ConstructorBinding
data class SwaggerContactProp(val mail: String, val url: String, val name: String)

그리고.applicatiom.yml:


swagger:
  title: Cards
  version: 1.0
  description: Documentation for API
  contact:
    mail: email@gmail.com
    url: some-url.com
    name: COLABA card

또한 추가하는 것도 잊지 마십시오.build.gradle.kts:

                implementation("io.springfox:springfox-swagger2:$swagger")
                implementation("io.springfox:springfox-swagger-ui:$swagger")
                implementation("io.springfox:springfox-bean-validators:$swagger")

저는 저 자신을 위한 몇 가지 가능한 해결책을 찾았습니다.아마도 다른 누군가에게 도움이 될 것입니다.


세트springdoc.swagger-ui.path직접적으로

간단한 방법은 속성을 설정하는 것입니다.springdoc.swagger-ui.path=/custom/path당신이 하드 코딩을 할 수 있다면 완벽하게 작동할 것입니다.swagger응용 프로그램의 경로입니다.


재정의springdoc.swagger-ui.path소유물

기본값을 변경할 수 있습니다.swagger-ui프로그래밍 방식으로 경로:사용ApplicationListener<ApplicationPreparedEvent>아이디어는 간단합니다. 오버라이드.springdoc.swagger-ui.path=/custom/pathSpring Boot 응용 프로그램이 시작되기 전에.

@Component
public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> {

    @Override
    public void onApplicationEvent(final ApplicationPreparedEvent event) {
        ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
        Properties props = new Properties();
        props.put("springdoc.swagger-ui.path", swaggerPath());
        environment.getPropertySources()
                .addFirst(new PropertiesPropertySource("programmatically", props));
    }

    private String swaggerPath() {
        return "/swagger/path"; //todo: implement your logic here.
    }
}

이 경우 응용프로그램을 시작하기 전에 수신기를 등록해야 합니다.

@SpringBootApplication
@OpenAPIDefinition(info = @Info(title = "APIs", version = "0.0.1", description = "APIs v0.0.1"))
public class App {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(App.class);
        application.addListeners(new SwaggerConfiguration());
        application.run(args);
    }
}

컨트롤러를 사용하여 리디렉션

또한 자신의 컨트롤러를 등록하고 제안된 대로 간단한 리디렉션을 수행할 수 있습니다.

리디렉션 코드:Spring WebFlux응용 프로그램:

@레스트 컨트롤러공용 클래스 스웨거 엔드포인트 {}
@GetMapping("/custom/path")public Mono<Void> api(ServerHttpResponse) {대답.setStatusCode(HttpStatus).영구_REDIRECT);
response.getHeaders().setLocation(URI.create("/swagger-ui.html"));응답을 반환합니다.set Complete();}}

이러한 접근 방식의 문제 - 주소로 호출해도 서버가 응답합니다."/swagger-ui.html".

당신은 이 코드를 사용할 수 있습니다, 그것은 저에게 효과가 있었습니다.

package com.swagger.api.redirect;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

public class SwaggerApiReDirector implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/documentation/v2/api-docs", "/v2/api-docs");
        registry.addRedirectViewController("/documentation/configuration/ui", "/configuration/ui");
        registry.addRedirectViewController("/documentation/configuration/security", "/configuration/security");
        registry.addRedirectViewController("/documentation/swagger-resources", "/swagger-resources");
        registry.addRedirectViewController("/documentation/swagger-resources/configuration/ui", "/swagger-resources/configuration/ui");
        registry.addRedirectViewController("/documentation", "/documentation/swagger-ui.html");
        registry.addRedirectViewController("/documentation/", "/documentation/swagger-ui.html");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/documentation/**").addResourceLocations("classpath:/META-INF/resources/");
    }
}

스프링 부트를 사용하는 경우 application.properties 파일을 업데이트하고 여기에 기록하십시오.

server.servlet.context-path=/myapi

당신이 원하는 대로 당신을 리디렉션할 것입니다.

언급URL : https://stackoverflow.com/questions/57193286/how-to-change-swagger-ui-html-default-path

반응형