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

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

  1. Spring Boot学习笔记---Spring Boot 基础及使用idea搭建项目

    最近一段时间一直在学习Spring Boot,刚进的一家公司也正好有用到这个技术.虽然一直在学习,但是还没有好好的总结,今天周末先简单总结一下基础知识,等有时间再慢慢学习总结吧. Spring Boo ...

  2. Spring Boot学习笔记——Spring Boot与MyBatis的集成(项目示例)

    1.准备数据库环境 # 创建数据库 CREATE DATABASE IF NOT EXISTS zifeiydb DEFAULT CHARSET utf8 COLLATE utf8_general_c ...

  3. Vue+Spring Boot 前后端分离的商城项目开源啦!

    新蜂商城 Vue 移动端版本开源啦! 去年开源新蜂商城项目后,就一直在计划这个项目 Vue 版本的改造,2020 年开始开发并且自己私下一直在测试,之前也有文章介绍过测试过程和存在的问题,修改完成后, ...

  4. 《Asp.Net Core3 + Vue3入坑教程》-Net Core项目搭建与Swagger配置步骤

    简介 <Asp.Net Core3 + Vue3入坑教程> 此教程仅适合新手入门或者前后端分离尝试者.可以根据图文一步一步进操作编码也可以选择直接查看源码.每一篇文章都有对应的源码 教程后 ...

  5. Spring Boot实践——基础和常用配置

    借鉴:https://blog.csdn.net/j903829182/article/details/74906948 一.Spring Boot 启动注解说明 @SpringBootApplica ...

  6. Spring boot运行原理-自定义自动配置类

    在前面SpringBoot的文章中介绍了SpringBoot的基本配置,今天我们将给大家讲一讲SpringBoot的运行原理,然后根据原理我们自定义一个starter pom. 本章对于后续继续学习S ...

  7. Spring Boot源码探索——自动配置的内部实现

    前面写了两篇文章 <Spring Boot自动配置的魔法是怎么实现的>和 <Spring Boot起步依赖:定制starter>,分别分析了Spring Boot的自动配置和起 ...

  8. Spring Boot Mybatis简单使用

    Spring Boot Mybatis简单使用 步骤说明 build.gradle:依赖添加 application.properties:配置添加 代码编写 测试 build.gradle:依赖添加 ...

  9. 自定义的Spring Boot starter如何设置自动配置注解

    本文首发于个人网站: 在Spring Boot实战之定制自己的starter一文最后提到,触发Spring Boot的配置过程有两种方法: spring.factories:由Spring Boot触 ...

随机推荐

  1. 截图原理(一)——Android自动化测试学习历程

    把两节的内容汇总起来,第一节讲的是如何在apk中直接进行截屏,用到了Robotium的Solo类的takeScreenShot方法,有一个小的demo,以及从方法一直往里钻,知道它具体是怎么进行截屏的 ...

  2. echarts折线图Demo

    echarts链接:http://echarts.baidu.com/examples/editor.html?c=line-stack 黑底代码:http://gallery.echartsjs.c ...

  3. Android的事件分发机制

    public boolean dispatchTouchEvent(MotionEvent event) 通过方法名我们不难猜测,它就是事件分发的重要方法.那么很明显,如果一个MotionEvent传 ...

  4. c#设计模式3抽象工厂模式(Abstract Factory)

    #region 坦克系列 abstract class Tank { abstract public void Go(); } /// <summary> /// 越野车 /// < ...

  5. istio promethus收集不到数据

    1.重新apply istio.yaml kubectl apply -f install/kubernetes/istio.yaml kubectl get metrics.config.istio ...

  6. iOS.WWDC

    1. ASCIIwwdc: Searchable full-text transcripts of WWDC sessions http://asciiwwdc.com

  7. hihoCoder1159 扑克牌

    一道记忆化搜索 原题链接 和着色方案很像,这里就不详细阐述,可以去我博客里的着色方案里看. 但要注意本题不一样的是同种面值的牌花色不同,所以在转移时还需要乘上同种面值的牌的个数. #include&l ...

  8. Scrapy-Redis分布式策略

    Scrapy-Redis分布式策略 原理图: 假设有四台电脑:Windows 10.Mac OS X.Ubuntu 16.04.CentOS 7.2,任意一台电脑都可以作为 Master端 或 Sla ...

  9. DEDE 首页调用指定栏目链接的代码

    {dede:type typeid='6'} <a href='[field:typelink /]' target="_blank" >更多</a> {/ ...

  10. 清晰易懂!关于PS入门的超详细笔记!

    给大家分享一篇关于PS入门的超详细笔记!原理讲解清晰明了,虽不是新版本解析,但都是新手学习PS必掌懂的一些知识点,灰常的实用,转走收藏学习! 编辑:千锋UI设计 来源:PS学堂