catalogue
Integrate Swagger dependent packages
Create Swagger related Docket Bean
Add the annotation of Swagger in the controller layer to let spring automatically load and identify
Create SpringBoot project
This time we use IDEA as a development tool. A great advantage of IDEA is that it can build a project, and then there are multiple module s below. This feature is very convenient for us to do Java development, especially for micro service development.
Create a new project
We first adopt the default maven project, and then add what components we need later.
In this way, we have built a projec, which is mainly used for directory function, not business code. Therefore, in the future, we will add the corresponding module to it.
Create a new module
The interface of different versions of IDEA may be a little different, but the basic meaning is probably the same, so if you encounter friends with different interfaces, you can carefully look at them and compare them.
In some versions of IDEA, "Spring Web" may be "WEB". In fact, they are the same.
If you don't have a maven library on your computer, you may have to wait a while.
It can be seen from the above figure that the module has been successfully created. Let's test it to see whether it has been successfully built.
Let's run it and see the effect.
The default is port 8080. Let's visit it in the browser.
http://localhost:8080/
If the above interface appears, it proves that it has been successfully built.
Prepare database
Because we want to integrate Mybatis, which belongs to the persistence layer framework, we need to prepare the Mysql database environment in advance. I won't elaborate on the Mysql installation tutorial here. You can find the tutorial online or in my blog.
New database
New user table t_user
I created the above through database tools. You can also create it through commands.
CREATE TABLE `t_user` ( `id` int NOT NULL AUTO_INCREMENT COMMENT 'id,Primary key', `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT 'user name', `age` int DEFAULT NULL COMMENT 'Age', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Insert test data
In order to facilitate debugging, we first insert some test data.
You can also implement it through command statements.
INSERT INTO `t_user` (`name`, `age`) VALUES ('zhangsan', '20') INSERT INTO `t_user` (`name`, `age`) VALUES ('lisi', '25')
Integrate Mybatis
Add corresponding Jar package
Add Mybatis related packages first:
<!-- Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
Since the database we choose is mysql, we also need to add MySQL related packages.
<!-- Mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
code implementation
SpringBoot is mainly used for web projects, so we will complete the coding from the web project development process this time.
Generally speaking, web projects are generally divided into three layers: controller, service and dao. So where should we start? To be honest, there are no mandatory requirements, but most developers may start from the controller layer and write to the dao side. Then go back and improve the controller. But in order to demonstrate this time, our business code will be relatively simple. I'll write it in reverse and write dao first. Before writing dao layer, I post the package structure of the project.
User
We use a classic entity class this time, which is similar to the T of the database_ The user table does not match.
package com.ispeasant.demo.entity; /** * User Entity class */ public class User { private int id; // id private String name; // user name private int age; // Age public int getId() { return id; } public String getName() { return name; } public int getAge() { return age; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } }
In projects, we often need to create entity classes. Generally, we need to write get/set methods. We should flexibly apply development work and improve coding efficiency.
dao(UserMapper)
package com.ispeasant.demo.dao; import com.ispeasant.demo.entity.User; import org.apache.ibatis.annotations.Mapper; /** * UserMapper */ @Mapper public interface UserMapper { User getUserById(int id); }
It should be noted here that the "@ Mapper" annotation must be used, and the corresponding mapper.xml file needs to be configured, otherwise spring cannot scan it.
mapper.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ispeasant.demo.dao.UserMapper"> <resultMap type="User" id="UserMap"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="INTEGER"/> </resultMap> <select id="getUserById" parameterType="INTEGER" resultMap="UserMap"> select * from t_user where 1=1 and id = #{id,jdbcType=INTEGER} </select> </mapper>
Split Description:
<mapper namespace="com.ispeasant.demo.dao.UserMapper">
This part is to directly copy the full path corresponding to your dao interface.
<resultMap type="User" id="UserMap"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="age" property="age" jdbcType="INTEGER"/> </resultMap>
This is done on demand, and there may be several different definitions. Some friends may find it difficult to understand this part. That's what I told my team. You can regard this part as an entity object in the configuration file to facilitate data interaction.
<select id="getUserById" parameterType="INTEGER" resultMap="UserMap"> select * from t_user where 1=1 and id = #{id,jdbcType=INTEGER} </select>
The id of the select tag should correspond to the method of UserMapper, and then write the corresponding business sql logic in it.
UserService
package com.ispeasant.demo.service; import com.ispeasant.demo.entity.User; public interface UserService { User getUserById(int id); }
In the Java EE code specification, we generally encapsulate the service layer into two layers, one is the interface layer and the other is the implementation layer, which can facilitate the decoupling of business code.
UserService
package com.ispeasant.demo.service.impl; import com.ispeasant.demo.dao.UserMapper; import com.ispeasant.demo.entity.User; import com.ispeasant.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserSeviceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(int id) { User user = userMapper.getUserById(id); return user; } }
We need to implement the UserService interface first and rewrite the methods inside. The UserMapper needs to be loaded automatically and annotated with "@ Autowired".
On the class, we need to adopt the "@ Service" annotation, which will be injected into the controller layer by spring.
UserController
package com.ispeasant.demo.controller; import com.ispeasant.demo.entity.User; import com.ispeasant.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/getUserById") public User getUserById(int id){ User user = userService.getUserById(id); return user; } }
The Controller layer is a little similar to the service layer. It also needs to automatically load UserService with "@ Autowired" annotation.
On the top of the class, you also need to add "@ RestController", which is the combination of two annotations of responsebobby + controller.
@GetMapping encapsulates API interface definitions@ The GetMapping annotation maps HTTP GET requests to specific handler methods. It is a combined annotation used as a shortcut to @ RequestMapping(method = RequestMethod.GET).
application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://10.18.0.57:3306/springbootmybatisDB spring.datasource.username=root spring.datasource.password=123456 mybatis.type-aliases-package=com.ispeasant.demo.entity mybatis.mapperLocations=classpath:mappers/*.xml
Finally, you need to configure database related information. Since I use mysql8, the driver should use "com.mysql.cj.jdbc.Driver". If it is a database of other lower versions, you can use "com.mysql.jdbc.Driver".
Finally, the entity package path and mapper file path should be configured there (through configuration).
verification
Open the following link in the browser:
http://localhost:8080/getUserById?id=1
If the following data is returned, the integration is successful. Later, you can develop other businesses according to your actual needs.
{"id":1,"name":"zhangsan","age":20}
Integrate Swagger
The last part is the integration of Swagger. In the actual project development, the role of Java EE project is more and more inclined to interface, providing interfaces for multiple terminals, such as web terminal, mobile terminal, applet terminal and so on.
What is Swagger?
The official website describes this:
API Development for Everyone
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset. Find out how Swagger can help you design and document your APIs at scale.
Swagger is used for API development, which is similar to the API documents we wrote before, which is convenient for the collaborative development of the development team.
effect:
-
Automatically generate interface documentation.
-
Interface test
Integrate Swagger dependent packages
In POM Add the following to the XML file.
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
Create Swagger related Docket Bean
package com.ispeasant.demo.config; import io.swagger.annotations.ApiOperation; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SpringFoxSwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) .build().apiInfo(apiInfo()) ; } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("RESTful API") .description("Basic management") .termsOfServiceUrl("") .version("1.0") .build(); } }
Let's run the code first to see the effect. Directly run the "DemoApplication" class, and then enter the link of Swagger UI in the browser: http://localhost:8080/swagger-ui.html
The above figure shows that we have successfully integrated swagger. Let me explain the above code first, and then get some API interfaces to experience it.
We use the createRestApi() method to create a Docket Bean, and then use the apiInfo() method to create the basic information of the whole API, that is, the information we see above.
@Configuration and @ EnableSwagger2 annotations must be declared, otherwise spring cannot load and recognize them.
We can also use our browser to open the following link to view the swagger metadata that has been generated to describe the API.
http://localhost:8080/v2/api-docs
{"swagger":"2.0","info":{"description":"test","version":"1.0","title":"API Demo"},"host":"localhost:8080","basePath":"/"}
It's a little hard to see the content, so we'd better use the UI interface at the top.
Add the annotation of Swagger in the controller layer to let spring automatically load and identify
package com.ispeasant.demo.controller; import com.ispeasant.demo.entity.User; import com.ispeasant.demo.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @Api(value = "User module", description = "User module interface") public class UserController { @Autowired private UserService userService; @RequestMapping(value = "/getUserById", method = RequestMethod.GET) @ApiOperation(value = "According to user ID Get user", notes = "query") @ApiImplicitParams({@ApiImplicitParam(name = "id",value = "Primary key id",required = true,paramType = "query",dataType = "int")}) public User getUserById(int id) { User user = userService.getUserById(id); return user; } }
We can also test the interface in Swagger's web UI.
As can be seen from the above figure, we have successfully assembled Swagger.
I have put this code on Baidu. If necessary, please follow my official account and reply to "2020102802" to get the download link.