[springboot development monomer web shop] 4. Swagger generation Javadoc

Swagger Generates JavaDoc

In our daily work, especially in the now front-end and back-end split mode, the interface provides the communication between our front-end and back-end developers.
Costs have risen dramatically, as communication is inadequate and unpredictable events become routine.Especially for many developers
If you are not good at communication, the result will make you particularly painful and itchy.
Swagger was created to end the spread of war and to improve developer satisfaction.

What is Swagger

Swagger for Everyone
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset.
Swagger open source and pro tools have helped millions of API developers, teams, and organizations deliver great APIs.

In short, it means using toolsets to simplify API development for users, teams, and businesses.

Integrated Swagger

I chose to use swagger-spring-boot-starter in the system.

This project utilizes Spring Boot's automated configuration feature to quickly introduce swagger2 into spring boot applications to generate API documents and simplify native integration code using swagger2.
I can see that I'm teaching people to be lazy. That's not a good thing.

Add Dependency

        <!--integration Swagger2-->
        <dependency>
            <groupId>com.spring4all</groupId>
            <artifactId>swagger-spring-boot-starter</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>

Click the version number to enter swagger-spring-boot-starter/1.9.0.RELEASE/swagger-spring-boot-starter-1.9.0.RELEASE.pom to see the version information it depends on.

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.java>1.8</version.java>
        <version.swagger>2.9.2</version.swagger>
        <version.spring-boot>1.5.10.RELEASE</version.spring-boot>
        <version.lombok>1.18.6</version.lombok>
    </properties>

Enable functionality

Add the @EnableSwagger2Doc annotation on our startup class ApiApplication

@SpringBootApplication
@MapperScan(basePackages = "com.liferunner.mapper")
@ComponentScan(basePackages = {"com.liferunner", "org.n3r.idworker"})
@EnableSwagger2Doc //Start Swagger
public class ApiApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(ApiApplication.class)
                .run(args);
    }

    @Autowired
    private CORSConfig corsConfig;

    /**
     * Register cross-domain configuration information
     *
     * @return {@link CorsFilter}
     */
    @Bean
    public CorsFilter corsFilter() {
        val corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin(this.corsConfig.getAllowOrigin());
        corsConfiguration.addAllowedMethod(this.corsConfig.getAllowedMethod());
        corsConfiguration.addAllowedHeader(this.corsConfig.getAllowedHeader());
        corsConfiguration.setAllowCredentials(this.corsConfig.getAllowCredentials());

        val urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

Configuration Base Information

You can configure it through the properties file and the yml/yaml file.

# Configure swagger2
swagger:
  enabled: true #Whether swagger is enabled, default:true
  title: Actual E-commerce api platform
  description: provide Online retailers API
  version: 1.0.0.RC
  license: Apache License, Version 2.0
  license-url: https://www.apache.org/licenses/LICENSE-2.0.html
  terms-of-service-url: http://www.life-runner.com
  contact:
    email: magicianisaac@gmail.com
    name: Isaac-Zhang
    url: http://www.life-runner.com
  base-package: com.liferunner
  base-path: /**

Phase effect one

Run our api project and enter http://localhost:8088/swagger-ui.html in the browser, as follows:

As you can see, the information we configured in the yml file is displayed at the top of the page, click User Management:

As you can see from the diagram above, our/users/create interface is displayed, and the parameters to be passed in, the type of request, and so on, are already shown in the diagram above.
But what does the parameter to be passed mean, it's all our field information, how do we make it more friendly to the caller?Let's continue
Perfect our document information:

Perfect description information

When we create a user, we need to pass a com.liferunner.dto.UserRequestDTO object with the following properties:

@RestController
@RequestMapping(value = "/users")
@Slf4j
@Api(tags = "user management")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation(value = "User Details", notes = "Query Users")
    @ApiIgnore
    @GetMapping("/get/{id}")
    //@GetMapping ('/{id}') If this is set here, swagger will come in every request, which is a bug
    public String getUser(@PathVariable Integer id) {
        return "hello, life.";
    }

    @ApiOperation(value = "Create User", notes = "User Registration Interface")
    @PostMapping("/create")
    public JsonResponse createUser(@RequestBody UserRequestDTO userRequestDTO) {
        //...
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(value = "Create User DTO", description = "Parameter object required for user registration")
public class UserRequestDTO {
    @ApiModelProperty(value = "User name", notes = "username", example = "isaaczhang", required = true)
    private String username;
    @ApiModelProperty(value = "Registration Password", notes = "password", example = "12345678", required = true)
    private String password;
    @ApiModelProperty(value = "Confirm Password", notes = "confimPassword", example = "12345678", required = true)
    private String confirmPassword;
}

As you can see, we have many notes beginning with @Apixxx, which Swagger has provided us with explanatory fields and documentation notes.

  • @Api indicates an external API
  • @ApiIgnore means not exposed and can be used for classes and methods
  • @ApiOperation is the CURD action under an API
  • @ApiResponses describes possible exceptions to the operation
  • @ApiParam describes the single parameter information passed
  • Property descriptions used by @ApiModel to describe Java objects
  • @ApiModelProperty Description object Field Description
    All uses, you can go to the specific class of the relevant annotation to see all the attribute information, which is relatively simple, there is no specific description here.To see more property descriptions,
    You can enter: Swagger property description portal.

After configuring, restart the application and refresh the UI page:

The red boxes in the picture above circle the instructions we reconfigured, which are simple enough to understand ~

Integrate a better UI interface

For API instructions, the information we've just mentioned is good enough, but as a technology, what we should be looking for is a more extreme level, where the UI interfaces mentioned above are available in large quantities
Friendly has such a missing shortage when it comes to user interface. Now let's introduce a better open source Swagger UI, please swagger-bootstrap-ui.

As we can see from the figure above, the number of tars for this UI has exceeded 1.1K, which proves that it is excellent. Let's unravel its true face of Lushan.

Integration Dependency

Just add the following dependency code to our expensive-shop\pom.xml:

        <!--A new swagger ui-->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.6</version>
        </dependency>

Preview Effect

After adding the dependencies, just restart our application and visit http://localhost:8088/doc.html as follows:

Click Create User:

Are the above effects more in line with our aesthetics?
So far, the effect of using Swagger to dynamically generate API s has been fully demonstrated, but what if one day we want to integrate with a customer who can't connect to view our website?
Do you still want to hand-write a document to them?So we're not just as painful!!!
As programmers, we can never allow this to happen!
Let's just keep looking.

Generate offline documents

Since we've added so much explanatory information to our code, is there a way to help us generate an offline document?The answer is yes.

Open source project swagger2markup

A Swagger to AsciiDoc or Markdown converter to simplify the generation of an up-to-date RESTful API documentation by combining documentation that's been hand-written with auto-generated API documentation.

Source Port
documents portal

Swagger2Markup is designed to convert Swagger's autogenerated documents into several popular formats for offline use
Format: AsciiDoc, HTML, Markdown, Confluence

Generate AsciiDoc document using MAVEN plug-in

Add the following dependency code to mscx-shop-api\pom.xml:

<build>
        <plugins>
            <!--generate AsciiDoc File(swagger2markup)-->
            <plugin>
                <groupId>io.github.swagger2markup</groupId>
                <artifactId>swagger2markup-maven-plugin</artifactId>
                <version>1.3.3</version>
                <configuration>
                    <!--Here's to start our project and grab api-docs Return results of-->
                    <swaggerInput>http://localhost:8088/v2/api-docs</swaggerInput>
                    <outputDir>src/docs/asciidoc/generated-doc</outputDir>
                    <config>
                        <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage>
                    </config>
                </configuration>
            </plugin>
        </plugins>
    </build>
  • <swaggerInput>http://localhost:8088/v2/api-docs</swaggerInput>is to obtain our api JSON data, as shown below:
  • <outputDir>src/docs/asciidoc/generated-doc</outputDir>Set the directory address that we want to generate

Execute command:

expensive-shop\mscx-shop-api>mvn swagger2markup:convertSwagger2markup

If you think the command is too long, you can also click IDEA => Maven => mscx-shop-api => Plugins => swagger2markup => swagger2markup:convertSwagger2markup to execute it, as shown below:

The results are as follows:

The adoc file is generated, so let's use it to generate html

Generating HTML using the MAVEN plug-in

Add the following dependency code to mscx-shop-api\pom.xml:

            <!--generate HTML File-->
            <plugin>
                <groupId>org.asciidoctor</groupId>
                <artifactId>asciidoctor-maven-plugin</artifactId>
                <version>1.5.6</version>
                <configuration>
                    <sourceDirectory>src/docs/asciidoc/generated-doc</sourceDirectory>
                    <outputDirectory>src/docs/asciidoc/html</outputDirectory>
                    <backend>html</backend>
                    <sourceHighlighter>coderay</sourceHighlighter>
                    <attributes>
                        <toc>left</toc>
                    </attributes>
                </configuration>
            </plugin>
  • <sourceDirectory>src/docs/asciidoc/generated-doc</sourceDirectory>The source file directory is specified as the adoc generated in our previous section
  • <output Directory>src/docs/asciidoc/html</output Directory>Specify output directory

Execute the build command:

\expensive-shop\mscx-shop-api>mvn asciidoctor:process-asciidoc

The results are as follows:

Open overview.html as follows:

So far, our documents have all been generated!

Next Section Forecast

In the next section, we will continue to develop a partial display of our user logins and homepage information. Any development components used in the process will be introduced in a special section, brothers panic!

gogogo!

Tags: Java Spring Maven xml

Posted on Thu, 07 Nov 2019 16:46:38 -0800 by lamurio