Spring Boot项目简单上手+swagger配置+项目发布(可能是史上最详细的)

Spring Boot项目简单上手+swagger配置

1、项目实践

项目结构图

项目整体分为四部分:1、source code 2、sql-mapper 3、application.properties  4、pom.xml

工作量主要集中在1,2;3,4主要是一些配置项,依赖库的添加。

(1)建表语句:

CREATE TABLE `city` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市编号',
  `province_id` int(10) unsigned NOT NULL COMMENT '省份编号',
  `city_name` varchar(25) DEFAULT NULL COMMENT '城市名称',
  `description` varchar(25) DEFAULT NULL COMMENT '描述',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=81 DEFAULT CHARSET=utf8;

(2)controller 代码

package org.spring.springboot.controller;

import static springfox.documentation.builders.PathSelectors.regex;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.ArrayList;
import java.util.List;

import org.spring.springboot.domain.City;
import org.spring.springboot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by bysocket on 07/02/2017.
 */
@RequestMapping("/api")
@RestController
public class CityRestController {

    @Autowired
    private CityService cityService;
    

    @RequestMapping(value = "/checkcity", method = RequestMethod.GET, produces = "application/json")
    public List<City> findOneCity(@RequestParam(value = "cityName", required = true) String cityName) {
        return cityService.findCityByName(cityName);
    }

//    @RequestMapping(value = "/api/addcity", method = RequestMethod.POST)
//    public int addCity(@RequestParam(value = "City", required = true) City city) {
//        return cityService.save(city);
//    }

    @RequestMapping(value = "/addcity", method = RequestMethod.POST)
    public int addCity(@RequestBody City city) {
        return cityService.save(city);
    }
}

(3)application.properties文件配置

## 数据库连接
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=111111
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 配置
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapper/*.xml

(4)pom.xml文件添加依赖配置

<groupId>springboot</groupId>
    <artifactId>springboot-mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-mybatis :: 整合 Mybatis Demo</name>
   <!-- <packaging>jar</packaging>-->
    <packaging>war</packaging>

    <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
        <mysql-connector>5.1.39</mysql-connector>
    </properties>

    <dependencies>

        <!-- Spring Boot Web 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Test 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Spring Boot Mybatis 依赖 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot}</version>
        </dependency>

        <!-- MySQL 连接驱动依赖 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector}</version>
        </dependency>
        
        <!--因配置外部TOMCAT 而配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <!-- 打包war增加的build模块 -->
    <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>repackage</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
</build>
    

参考文章

https://www.w3cschool.cn/springboot/springboot-fwsi24l6.html

2、spring boot + swagger

这部分主要为项目添加最近比较流行的swagger,就是通过注释,使项目自动生成接口文档

在原来的项目的基础上,主要增加了两部分内容,1,实体类 为每个参数增加“注释”;2,在controller类中添加注释;3,添加依赖;如下图

首先添加swagger依赖,执行maven—>update projrct

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
    <scope>compile</scope>
</dependency>

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

1,实体类添加的内容为红圈处

2,参见下面代码粗红体字

package org.spring.springboot.controller;

import static springfox.documentation.builders.PathSelectors.regex;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.ArrayList;
import java.util.List;

import org.spring.springboot.domain.City;
import org.spring.springboot.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by bysocket on 07/02/2017.
 */
@RequestMapping("/api")
@RestController
@EnableSwagger2
public class CityRestController {

    @Autowired
    private CityService cityService;
    
    @Bean
    public Docket demoApi() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("org.spring.springboot.controller")).paths(regex("/api.*")).build()
                .apiInfo(metaData());

    }

    private ApiInfo metaData() {
        ApiInfo apiInfo = new ApiInfo("Spring Boot REST API Demo by Torre Yang", "Spring Boot REST API for Simple Demo", "1.0",
                "termsOfServiceUrl",
                new Contact("Torre Yang", "https://github.com/Testworm/",
                        "klyweiwei@163.com"),
                "Apache License Version 2.0", "https://www.apache.org/licenses/LICENSE-2.0");
        return apiInfo;
    }

    @RequestMapping(value = "/checkcity", method = RequestMethod.GET, produces = "application/json")
    public List<City> findOneCity(@RequestParam(value = "cityName", required = true) String cityName) {
        return cityService.findCityByName(cityName);
    }

//    @RequestMapping(value = "/api/addcity", method = RequestMethod.POST)
//    public int addCity(@RequestParam(value = "City", required = true) City city) {
//        return cityService.save(city);
//    }
    
    @ApiOperation(value = "增加城市", response = org.spring.springboot.domain.City.class, responseContainer = "city")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved list"),
            @ApiResponse(code = 401, message = "You are not authorized to view the resource"),
            @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
            @ApiResponse(code = 404, message = "The resource you were trying to reach is not found") })
    @RequestMapping(value = "/addcity", method = RequestMethod.POST)
    public int addCity(@RequestBody City city) {
        return cityService.save(city);
    }
    
    
}

注意:如果是服务器通过java -jar  ***.jar,则swagger地址为:http://192.168.5.129:8080/swagger-ui.html#/

如果是发布到tomcat,则需要添加webapps下面的项目文件名到端口后面,即标红处

http://192.168.5.129:8080/springboot/swagger-ui.html#/

参考文档:

https://www.jianshu.com/p/edaeb90c500c

3、springboot项目简单部署到服务器

项目的发布,可以有两种方式;1,war包放置tomcat下发布 2,打包成jar包发布至服务器

1、打包生成war包方法

(1)配置pom.xml文件,主要是增加配置;

    <packaging>war</packaging>
 <!--因配置外部TOMCAT 而配置-->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>

(2)重新build方法

package org.spring.springboot;

import org.mybatis.spring.annotation.MapperScan;
import org.spring.springboot.dao.CityDao;
import org.spring.springboot.domain.City;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

/**
 * Spring Boot 应用启动类
 */
// Spring Boot 应用的标识
@SpringBootApplication
// mapper 接口类扫描包配置
@MapperScan("org.spring.springboot.dao")
public class Application extends SpringBootServletInitializer{
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }
    public static void main(String[] args) {
        // 程序启动入口
        // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
        SpringApplication.run(Application.class,args);
    }
}

2、打包生产jar包;有两种方法

方法1,通过run as —>maven clean & maven install

第一次打包遇到一个问题;

启动SpringBoot的可执行jar 报错:target\spring-boot-hello-1.0-SNAPSHOT.jar中没有主清单属性

增加标红处依赖
<build>
<finalName>包名</finalName>  <!-- 定义包名> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
<!-- 下面这个部分是非常重要的>
<repositories> 
        <repository> 
            <id>spring-milestone</id> 
            <url>http://repo.spring.io/libs-release</url> 
        </repository> 
</repositories>

 

原因可能是因为:

查看了MANIFEST.MF,发现没有Main-Class属性,我想了一下,就试着去SpringBoot的官方文档上找找,果然有讲这一部分,spring-boot-maven-plugin的打包过程与直接使用maven-jar-plugin不同,所以我们在使用spring-boot-maven-plugin时需要指定的执行项,或者我们在打包时指定,使用 mvn package spring-boot:repackage来打包也可以执行。

方法2,通过run as —>maven build.. 打包

第一步:使用debug configurations 配置的方式打包

 

第二步:显示出debug configuratons 的页面,

1选中Maven  Bulid 下面的项目;

2 Goals选项中输入package

3 点击Debug按钮。

 

第三步:控制台输出了  1处的信息:BUILD SUCCESS

2项目的target文件夹下处理了 gateway.jar说明jar包打包完毕。

 

第四步测试jar包是否可用

使用命令窗体,切入到jar存在的目录;执行java –jar ***.jar

第五步查看启动结果

参考文献:

https://blog.csdn.net/qq_35893120/article/details/79898595

https://www.cnblogs.com/lfalex0831/p/8967428.html

https://blog.csdn.net/zhoucheng05_13/article/details/77915294

posted @ 2018-04-29 20:30  QualityAssurance21  阅读(1224)  评论(0编辑  收藏  举报