使用 maven 为 Micronaut 招摇招摇、maven、Micronaut

2023-09-07 14:28:13 作者:七寻笑

我想从 Spring Boot 2 切换到 Micronaut 框架.我在 Swagger 设置上苦苦挣扎.

I want to switch to the Micronaut framework from Spring Boot 2. And I am struggling with the Swagger settings.

在 Spring Boot 2 项目中,我有以下依赖项:

In Spring Boot 2 project I have the following dependencies:

    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>

和 SwaggerConfig.class:

and SwaggerConfig.class:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket swagger() {
        return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(getApiInfo())
            .select()
            .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
            .paths(PathSelectors.any())
            .build();
    }

    private ApiInfo getApiInfo() {
        return new ApiInfo("test",
            "",
            "",
            "",
            new Contact("", "https://test.test", ""),
            "",
            "");
    }
}

它可以完美地启动 swagger-ui 以及 Spring Boot 2 应用程序.

And it works perfectly starting up swagger-ui along with the Spring Boot 2 application.

我应该向 maven 添加哪些依赖项以及应该创建哪些类才能为 Micronaut 项目获得相同的结果?

Which dependencies should I add to maven and which classes should I create to obtain the same result for the Micronaut project?

推荐答案

假设应用程序已经创建,在 pom.xml 中添加以下内容

Assuming the application is already created, add the following to you pom.xml

<dependency>
  <groupId>io.swagger.core.v3</groupId>
  <artifactId>swagger-annotations</artifactId>
  <version>${swagger.version}</version>
  <scope>compile</scope>
</dependency>

属性 swagger.version 设置为 2.0.3

where the property swagger.version is set to 2.0.3

在 maven-compiler-plugin 中的 annotationProcessorPaths 中添加以下内容

add the following to you annotationProcessorPaths in the maven-compiler-plugin

<path>
  <groupId>io.micronaut.configuration</groupId>
  <artifactId>micronaut-openapi</artifactId>
  <version>${micronaut.version}</version>
</path>

然后将以下内容添加到您的 micronaut 路由器部分.

Then add the following to your micronaut router section.

micronaut:
    router:
        static-resources:
            swagger:
                paths: classpath:META-INF/swagger
                mapping: ${application.api.swagger.path}/**

如果您使用下面的配置,这将公开您在编译期间生成的 swagger/oas yml 文件.您当然可以将 ${application.api.swagger.path} 更改为 /api-docs/swagger 或您喜欢的其他内容.如文档中所述,您还可以在最初创建项目时执行以下 --features=swagger-java 来添加上述依赖项.

This will expose your swagger/oas yml file that is generated during compile, provided you use the configuration below. You can of course change the ${application.api.swagger.path} to just be /api-docs/swagger or something to your liking. As described in the docs, you can also do the following --features=swagger-java to add the above dependecies when you initially create the project.

如果您想从应用程序本身呈现 api 规范,那么您需要添加更多代码.下面的示例可能比它需要的更加充实,但出于我的目的,该应用程序充当了 swagger/oas 规范的中央渲染器.

If you want to render the api-specification from the application itself, then you need to add some more code. The following example is probably more fleshed out than it needs to be, but for my purpose the application serves as a central renderer for swagger/oas specifications.

首先根据你的需要添加一个控制器,并使用 @Hidden 对控制器进行注释,以确保它不会被注释处理器处理.

First add a controller for you swagger needs, and annotate the controller with @Hidden to make sure it doesn't get processed by the annotation processor.

@Hidden
@Controller("/api")
public class SwaggerController {

    @Inject
    SwaggerConfig config;

    @View("swagger/index")
    @Get
    public SwaggerConfig index() {
        return config;
    }
}

然后添加下面的配置类,从下面绑定属性

Then add the following configuration class, which binds the properties from below

@ConfigurationProperties(SwaggerConfig.PREFIX)
public class SwaggerConfig {

    public static final String PREFIX = "application.api.swagger";

    private String version;
    private String layout;
    private boolean deepLinking;
    private List<URIConfig> urls;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getLayout() {
        return layout;
    }

    public void setLayout(String layout) {
        this.layout = layout;
    }

    public boolean isDeepLinking() {
        return deepLinking;
    }

    public void setDeepLinking(boolean deepLinking) {
        this.deepLinking = deepLinking;
    }

    public List<URIConfig> getUrls() {
        return urls;
    }

    public void setUrls(List<URIConfig> urls) {
        this.urls = urls;
    }


    @ConfigurationProperties(URIConfig.PREFIX)
    public static class URIConfig {

        static final String PREFIX = "urls";

        private String name;
        private String url;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

}

上面的config类从application.yml中绑定了如下配置,但是需要放在micronaut具体配置之前.

The above config class binds the following configuration from application.yml, but needs to be placed before the micronaut specific configuration.

application:
    api:
        swagger:
            path: /api-docs/swagger
            version: 3.19.4
            layout: StandaloneLayout
            deepLinking: true
            urls:
            - name: ubw-rest
              url: /api-docs/swagger/ubw-rest-0.1.yml

完成后,将以下车把/胡子依赖添加到 pom

When that is done, add the following handlebars/mustache dependency to the pom

<dependency>
  <groupId>com.github.jknack</groupId>
  <artifactId>handlebars</artifactId>
  <version>4.1.0</version>
  <scope>runtime</scope>
</dependency>

在resources文件夹下,创建一个名为swagger的文件夹,然后创建一个包含以下内容的index.hbs文件.

Under the resources folder, create a folder named swagger, and then create an index.hbs file containing the following.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Swagger-ui</title>

    <link rel="icon" type="image/png" href="https://unpkg.com/swagger-ui-dist@{{version}}/favicon-32x32.png">
    <link rel="stylesheet" type="text/css" href="https://unpkg.com/swagger-ui-dist@{{version}}/swagger-ui.css">

    <script src="https://unpkg.com/swagger-ui-dist@{{version}}/swagger-ui-standalone-preset.js"></script>
    <script src="https://unpkg.com/swagger-ui-dist@{{version}}/swagger-ui-bundle.js"></script>
</head>
<body>
    <div id="swagger-ui"></div>
    <script>
        window.onload = function() {
            var ui = SwaggerUIBundle({
                urls: [{{#each urls}}
                    {
                        name: "{{name}}",
                        url: "{{url}}"
                    }{{#unless @last}},{{/unless}}{{/each}}
                ],
                dom_id: '#swagger-ui',
                deepLinking: {{deepLinking}},
                presets: [
                    SwaggerUIBundle.presets.apis,
                    SwaggerUIStandalonePreset
                ],
                plugins: [
                    SwaggerUIBundle.plugins.DownloadUrl
                ],
                layout: "{{layout}}"
            });
            window.ui = ui
        }
    </script>
</body>
</html>

最后,在应用程序主类中,添加@OpenApiDefinition注解,使注解处理器能够扫描整个应用程序.

Finally, in the application main class, add the @OpenApiDefinition annotation to enable the annotation processor to scan the entire appliaction.

@OpenAPIDefinition(
        info = @Info(
                title = "swagger-server",
                version = "0.1",
                description = "My API",
                license = @License(name = "Apache 2.0")
        )
)
public class Application {

    public static void main(String[] args) {
        Micronaut.run(Application.class);
    }
}

关于 micronaut 1.0.0 中的注释处理器的一个建议是对象上的公共字段不会被公开,因此如果您想查看输入的架构或返回值.

A word of advice regarding the annotation processor as it stands in micronaut 1.0.0 is that public fields on an object will not be exposed, so you need to have getters/setters if you want to see the schema for the input or return values.

如果您想尝试上述运行示例,我有一个带有 swagger 服务器配置的 repo,位于此处 https://github.com/frehov/micronaut-swagger-server,其中包括发布带有要由 Swagger 呈现的 url 和名称对列表的帖子.

If you'd like to try out a running example of the above, I have a repo with the swagger server configuration located here https://github.com/frehov/micronaut-swagger-server which includes the ability to make a post with a list of url and name pairs to be rendered by Swagger.