Search code examples
spring-bootkotlinswaggeropenjdk-11

Swagger does not work when Application startup file is placed inside a package. Kotlin Springboot


My project directory structure is like following

└── activity
    ├── app
    │   └── ActivityApplication.kt
    ├── controller
    │   └── WelcomeMessageController.kt
    ├── exception
    │   ├── ActivityErrorResponse.kt
    │   ├── handler
    │   │   └── ActivityServiceExceptionHandler.kt
    │   └── response
    │       └── ResponseCode.kt
    ├── model
    │   └── WelcomeMessage.kt
    ├── repository
    │   └── WelcomeMessageRepository.kt
    ├── service
    │   └── WelcomeService.kt
    └── swagger
        └── SwaggerConfig.kt

When I move my ActivityApplication.kt file to root package i.e. directly under activity swagger page starts to work normally. However, when i move it inside a package (in this case app) then swagger page does not show anything but following error

Error: Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:

my swagger config looks like following

@Configuration
@EnableSwagger2
class SwaggerConfig {
    @Bean
    fun api(): Docket {
        return Docket(DocumentationType.SWAGGER_2)
                .pathProvider(object: RelativePathProvider(null) {
                    override fun getApplicationBasePath(): String {
                        return "/activity"
                    }
                })
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.activity.controller"))
                .build()
                .apiInfo(buildApiInfo())
    }

    private fun buildApiInfo(): ApiInfo? {
        return ApiInfo(
                ...)
    }
}

ActivityApplication.kt has only following code

@SpringBootApplication
class ActivityApplication

fun main(args: Array<String>) {
    runApplication<ActivityApplication>(*args)
}
  • Java Version: OpenJDK 11
  • Springfox-swagger2 version: 2.9.2

Solution

  • Spring Boot tries to find it's components in deeper packages. I.e. if you place @SpringBootApplication on activity.app.ActivityApplication, Spring Boot will only search under activity.app and won't go to activity.swagger, on any other packages.

    If you don't want to move you ActivityApplication to activity package, then you need to manually specify base packages in @SpringBootApplication annotation's scanBasePackages parameter: @SpringBootApplication(scanBasePackages = "activity").

    Note: it should be full package, e.g. mycompany.myproject.activity).