Springboot介绍以及整合mybatis

一 Springboot介绍

SpringBoot 是在Spring基础上实现自动配置的基础框架,快速帮助Spring整合各种第三方框架,让项目配置化繁为简,大幅提高开发效率。

Springboot自动配置原理:

Springboot特性:

依靠Spring

提供自动配置,告别XML,实现约定大于配置

内嵌Tomcat,无需外部署

提供各种Starter的jar,可以简化依赖配置

二 创建方式

1 通过网站

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LmRiXn9a-1576815335278)(file:///D:\内网通\讲师资料\课件\15_3_springboot\笔记\bootpic\wpsD3F6.tmp.jpg)]

2 通过idea的spring initialize

在里面选择不同的选项,生成项目后,会自动增加不同的jar包依赖

注意:根据网络状况,可能会提示无法连接

3 通过普通maven项目

三 springboot入门

1 创建工程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yPTe2dqm-1576815335283)(file:///D:\内网通\讲师资料\课件\15_3_springboot\笔记\bootpic\wpsD416.tmp.jpg)]

2 pom文件

spring-boot-starter-parent 作为父工程,提供SpringBoot和Spring的相关依赖定义。

spring-boot-starter-web 引入Web和WebMvc的相关依赖。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.1.5.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.rr</groupId>
   <artifactId>emysys_boot</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>emysys_boot</name>
   <description>Demo project for Spring Boot</description>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
      </dependency>
<dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
         <scope>test</scope>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

3 编写控制器类的方法

@SpringBootApplication
@Controller
public class Springboot01QuickstartApplication {
   @GetMapping("/hello")
   @ResponseBody
   public String hello(){
      return "hello world";
   }

   public static void main(String[] args) {
      SpringApplication.run(Springboot01QuickstartApplication.class, args);
   }

}

@SpringBootApplication中,主要包含下面的注解使用:

@SpringBootConfiguration继承自@Configuration,二者功能也一致,标注当前类是配置类,并会将当前类内声明的一个或多个以@Bean注解标记的方法的实例纳入到srping容器中,并且实例名就是方法名。
​ @EnableAutoConfiguration的作用启动自动的配置,SpringBoot根据添加的jar包来配置项目的默认配置,比如根据spring-boot-starter-web ,来判断你的项目是否需要添加了webmvc和tomcat,就会自动的帮你配置web项目中所需要的默认配置

@ComponentScan,扫描当前包及其子包下被@Component,@Controller,@Service,@Repository注解标记的类并纳入到spring容器中进行管理。

4 启动

在启动类中,右键->run …

控制台输出内容如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Krzg7QWH-1576815335283)(file:///D:\内网通\讲师资料\课件\15_3_springboot\笔记\bootpic\wpsD437.tmp.jpg)]

5 访问

http://localhost:8080/hello

6 项目结构

源码所在的包放在启动类文件所在的包下

static:放置静态资源

​ 静态资源路径是指系统可以直接访问的路径,且路径下的所有文件均可被用户通过浏览器直接读取。

​ 在Springboot中默认的静态资源路径有:classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

springboot中配置:spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

可以直接访问templates中的路经

​ springboot中配置:spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/

templates:Thymeleaf等模板文件

application.properties: 配置文件

注意:默认情况下,没有webapps,SpringBoot 官方推荐使用轻量级的Jar File 格式来打包和部署工程

四 模板文件使用

Thymeleaf、 freemarker

页面静态化

Thymeleaf 是Java服务端的模板引擎,与传统的JSP不同,Thymeleaf 可以使用浏览器直接打开,相当于打开html原生页面。

1 基本使用

1) 导包

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2) 修改配置文件

系统默认会在src/main/Java/resources目录下创建一个application.properties配置文件

#开发时建议将spring.thymeleaf.cache设置为false,否则会有缓存
spring.thymeleaf.cache=false
spring.thymeleaf.encoding=utf-8
spring.thymeleaf.prefix=classpath:/templetes/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.servlet.content-type=text/html

3) 编写模板文件

编写Thymeleaf模板文件和编写HTML5页面没有什么不同,Thymeleaf的特征是使用拓展属性,前缀是th(th:xx),通过拓展属性和服务端进行数据交互

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Thymeleaf</title>
    </head>
    <body>
        <h2>欢迎使用Thymeleaf</h2>
        <h2 th:text="${info}"></h2>
    </body>
</html>

4) 控制器方法

@GetMapping("/hello")
public String hello(Model model) {
    model.addAttribute("info", "hello world");
    return "index";
}

2 常用th:前缀的属性

关键字      功能介绍        案例
th:id      替换id          <input th:id="'xxx' + ${collect.id}"/>
th:text     文本替换        <p th:text="${collect.description}">description</p>
th:utext    支持html的文本替换   <p th:utext="${htmlcontent}">conten</p>
th:object    替换对象        <div th:object="${session.user}">
th:value    属性赋值        <input th:value="${user.name}" />
th:with    变量赋值运算        <div th:with="isEven=${prodStat.count}%2==0"></div>
th:style    设置样式            th:style="'display:' + @{(${sitrue} ? 'none' : 'inline-block')} + ''"
th:onclick    点击事件          th:οnclick="'getCollect()'"
th:each    属性赋值            tr th:each="user,userStat:${users}">
th:if    判断条件            <a th:if="${userId == collect.userId}" >
th:unless    和th:if判断相反        <a th:href="@{/login}" th:unless=${session.user != null}>Login</a>
th:href    链接地址              <a th:href="@{/login}" th:unless=${session.user != null}>Login</a> />
th:switch    多路选择 配合th:case 使用    <div th:switch="${user.role}">
th:case    th:switch的一个分支        <p th:case="'admin'">User is an administrator</p>
th:fragment    布局标签,定义一个代码片段,方便其它地方引用    <div th:fragment="alert">
th:include    布局标签,替换内容到引入的文件    <head th:include="layout :: htmlhead" th:with="title='xx'"></head> />
th:replace    布局标签,替换整个标签到引入的文件    <div th:replace="fragments/header :: title"></div>
th:selected    selected选择框 选中    th:selected="(${xxx.id} == ${configObj.dd})"
th:src    图片类地址引入          <img class="img-responsive" alt="App Logo" th:src="@{/img/logo.png}" />
th:inline    定义js脚本可以使用变量    <script type="text/javascript" th:inline="javascript">
th:action    表单提交的地址        <form action="subscribe.html" th:action="@{/subscribe}">
th:remove    删除某个属性        <tr th:remove="all"> 
                    1.all:删除包含标签和所有的孩子。
                    2.body:不包含标记删除,但删除其所有的孩子。
                    3.tag:包含标记的删除,但不删除它的孩子。
                    4.all-but-first:删除所有包含标签的孩子,除了第一个。
                    5.none:什么也不做。这个值是有用的动态评估。
th:attr    设置标签属性,多个属性可以用逗号分隔    比如 th:attr="src=@{/image/aa.jpg},title=#{logo}",此标签不太优雅,一般用的比较少。

2表达式

1)变量表达式${}

获取对象属性,例如:

th:value="${user.id}"
th:text="${info}"

2)选择变量表达式 *{}

先通过th:object 获取对象,然后使用th:xx = "*{}"获取对象属性,一般和form一起使用。

<form id="" th:object="${user}">
    <input id="id" name="id" th:value="*{id}"/>
    <input id="username" name="username" th:value="*{username}"/>
	<input id="password" name="password" th:value="*{password}"/>
</form>

3)链接表达式@{}

通过该表达式引用静态资源路径。例如:

<script th:src="@{/js/jquery/jquery.js}"></script>
<link th:href="@{/bootstrap/css/bootstrap.css}" rel="stylesheet" type="text/css">

注意:/ 表示相对web应用

4)片段表达式 ~{}

片段表达式拥有三种语法:

~{ viewName } 表示引入完整页面

~{ viewName ::selector} 表示在指定页面寻找片段 其中selector可为片段名、jquery选择器等

~{ ::selector} 表示在当前页寻找

首先通过th:fragment定制片段 ,然后通过th:replace 填写片段路径和片段名。例如:

<head th:fragment="static">
        <script th:src="@{/webjars/jquery/3.3.1/jquery.js}"></script>
</head>
<div th:replace="~{common/head::static}"></div>

在实际使用中,我们往往使用更简洁的表达,去掉表达式外壳直接填写片段名。例如:

<div th:replace="common/head::static"></div>

5)消息表达式

即通常的国际化属性:#{msg} 用于获取国际化语言翻译值。例如:

<title th:text="#{user.title}"></title>

配置多语言文件的路径和文件前缀

spring.messages.basename=i18n/messages

在template目录下,新建i8n目录,在该目录下放置多语言文件

多语言文件命名规则:

文件名_语言_.properties

3 内置对象

1)七大基础对象

${#ctx} 上下文对象,可用于获取其它内置对象。

${#vars}: 上下文变量。

${#locale}:上下文区域设置。

${#request}: HttpServletRequest对象。

${#response}: HttpServletResponse对象。

${#session}: HttpSession对象。

${#servletContext}: ServletContext对象。

2)常用的工具类

#strings:字符串工具类

#lists:List 工具类

#arrays:数组工具类

#sets:Set 工具类

#maps:常用Map方法。

#objects:一般对象类,通常用来判断非空

#bools:常用的布尔方法。

#execInfo:获取页面模板的处理信息。

#messages:在变量表达式中获取外部消息的方法,与使用#{…}语法获取的方法相同。

#uris:转义部分URL / URI的方法。

#conversions:用于执行已配置的转换服务的方法。

#dates:时间操作和时间格式化等。

#calendars:用于更复杂时间的格式化。

#numbers:格式化数字对象的方法。

#aggregates:在数组或集合上创建聚合的方法。

#ids:处理可能重复的id属性的方法。

4 迭代循环

th:each,遍历List集合,例如:

<div th:each="user:${userList}">
    账号:<input th:value="${user.username}"/>
    密码:<input th:value="${user.password}"/></div>

在集合的迭代过程还可以获取状态变量,只需在变量后面指定状态变量名即可,状态变量可用于获取集合的下标/序号、总数、是否为单数/偶数行、是否为第一个/最后一个。例如:

<div th:each="user,stat:${userList}">
  下标:<input th:value="${stat.index}"/>
    序号:<input th:value="${stat.count}"/>
    账号:<input th:value="${user.username}"/>
    密码:<input th:value="${user.password}"/>
</div>

如果缺省状态变量名,则迭代器会默认帮我们生成以变量名开头的状态变量 xxStat, 例如:

<div th:each="user:${userList}" >
  下标:<input th:value="${userStat.index}"/>
    序号:<input th:value="${userStat.count}"/>
    账号:<input th:value="${user.username}"/>
    密码:<input th:value="${user.password}"/>
</div>

5条件判断

条件判断通常用于动态页面的初始化,例如:

<div th:if="${age lt ‘10’}">
	<div>haha</div>
</div>

如果想取反则使用unless 例如:

<div th:unless="${age lt ‘10’}">
  <div>不存在..</div>
</div>

6 内联写法

如果需要在 JS中获取服务端返回的变量,格式为:[[${xx}]],该内联表达式仅在页面生效,引入的js文件中使用无效。

<script th:inline="javascript">
   var user = [[${user}]];`
   var APP_PATH = [[${#request.getContextPath()}]];
   var LANG_COUNTRY = [[${#locale.getLanguage()+'_'+#locale.getCountry()}]];
</script>

五 springboot+mybatis配置

1 pom文件

2 springboot的配置文件

默认自动创建项目时,名称为application.properties

server.servlet.context-path=/empsys

# mybatis配置
# 配置别名需要扫描的包
mybatis.type-aliases-package=com.qfedu.emp.entity
# 引入映射文件
mybatis.mapper-locations=classpath:mapper/*.xml

# 数据库配置
# 本例中,使用mysql的驱动是8.x的版本,注意driver-class-name,url中增加时区的配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/j1904?serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# 和druid相关的配置
#初始化时建立物理连接的个数
spring.datasource.druid.initial-size=5
#最小连接池数量
spring.datasource.druid.min-idle=5

配置文件还可以使用yml后缀(application.yml),这种方式,注意缩进

server:
  servlet:
    context-path: /empsys

mybatis:
  type-aliases-package: com.qfedu.emp.entity
  mapper-locations: classpath:mapper/*.xml

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/j1904?serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    druid:
      max-active: 20
      initial-size: 5
  thymeleaf:
    cache: false

3 启动类使用的注解

@SpringBootApplication
@MapperScan("com.rr.dao")// 扫描dao层

4 mybatis配置

导入jar

<!--  引入mybatis相关依赖,必须写版本号 -->
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!--  引入mysql相关依赖,如果不写版本号,引入的8.0以上版本
 可以设置为其他版本
 -->
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.45</version>
</dependency>

使用配置

mybatis.type-aliases-package=com.rr.entity
#mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.mapper-locations=classpath:com/qfedu/mapper/*.xml

5 druid配置

Mysql驱动版本5.*

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

如果5.*以上

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

1)使用druid-spring-boot-starter

导入jar

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid-spring-boot-starter</artifactId>
   <version>1.1.10</version>
</dependency>

配置

#初始化时建立物理连接的个数
spring.datasource.druid.initial-size=5
#最小连接池数量
spring.datasource.druid.min-idle=5
#最大连接池数量 maxIdle已经不再使用
spring.datasource.druid.max-active=20
#获取连接时最大等待时间,单位毫秒
spring.datasource.druid.max-wait=60000
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
spring.datasource.druid.test-while-idle=true
#既作为检测的间隔时间又作为testWhileIdel执行的依据
spring.datasource.druid.time-between-eviction-runs-millis=60000
#销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接
spring.datasource.druid.min-evictable-idle-time-millis=30000
#用来检测连接是否有效的sql 必须是一个查询语句
#mysql中为 select 'x'
#oracle中为 select 1 from dual
spring.datasource.druid.validation-query=select 'x'
#申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-borrow=false
#归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
spring.datasource.druid.test-on-return=false
#当数据库抛出不可恢复的异常时,抛弃该连接
spring.datasource.druid.exception-sorter=true
#是否缓存preparedStatement,mysql5.5+建议开启
#spring.datasource.druid.pool-prepared-statements=true
#当值大于0时poolPreparedStatements会自动修改为true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20
#配置扩展插件
spring.datasource.druid.filters=stat,wall
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
#合并多个DruidDataSource的监控数据
spring.datasource.druid.use-global-data-source-stat=true

2)直接导入druid的包 了解

导入jar

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.18</version>
</dependency>

自定义配置,key值是自定义的,无法自动配置,还需要手动编写配置类

spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000

spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

6 事务处理

默认不会开启事务

@EnableTransactionManagement可以不写,因为已经自动配置过了

导入jar包

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

1)在需要使用事务的类上,使用@Transactional注解

2)配置全局事务处理

@Aspect
@Configuration
public class GlobalTransaction {
    //写事务的超时时间为10秒
    private static final int TX_METHOD_TIMEOUT = 10;

    //restful包下所有service包或者service的子包的任意类的任意方法
    private static final String AOP_POINTCUT_EXPRESSION = "execution (* com.rr.service.impl.*.*(..))";

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Bean
    public TransactionInterceptor txAdvice() {

        /**
         * 这里配置只读事务
         */
        RuleBasedTransactionAttribute readOnlyTx = new RuleBasedTransactionAttribute();
        readOnlyTx.setReadOnly(true);
        readOnlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

        /**
         * 必须带事务
         * 当前存在事务就使用当前事务,当前不存在事务,就开启一个新的事务
         */
        RuleBasedTransactionAttribute requiredTx = new RuleBasedTransactionAttribute();
        //检查型异常也回滚
        requiredTx.setRollbackRules(
                Collections.singletonList(new RollbackRuleAttribute(Exception.class)));
        requiredTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        requiredTx.setTimeout(TX_METHOD_TIMEOUT);

        /***
         * 无事务地执行,挂起任何存在的事务
         */
        RuleBasedTransactionAttribute noTx = new RuleBasedTransactionAttribute();
        noTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);

        Map<String, TransactionAttribute> txMap = new HashMap<>();
        //只读事务
        txMap.put("get*", readOnlyTx);
        txMap.put("query*", readOnlyTx);
        txMap.put("find*", readOnlyTx);
        txMap.put("list*", readOnlyTx);
        txMap.put("count*", readOnlyTx);
        txMap.put("exist*", readOnlyTx);
        txMap.put("search*", readOnlyTx);
        txMap.put("fetch*", readOnlyTx);
        //无事务
        txMap.put("noTx*", noTx);
        //写事务
        txMap.put("add*", requiredTx);
        txMap.put("save*", requiredTx);
        txMap.put("insert*", requiredTx);
        txMap.put("update*", requiredTx);
        txMap.put("modify*", requiredTx);
        txMap.put("delete*", requiredTx);

        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        source.setNameMap(txMap);

        return new TransactionInterceptor(transactionManager, source);
    }

    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }
}


7 日志处理

1)处理jar包依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter</artifactId>
   <exclusions>
      <exclusion>
         <!-- 使用了log4j2,就要将spring-boot-starter-logging排除 -->
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-logging</artifactId>
      </exclusion>
   </exclusions>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <!-- springboot默认是用logback的日志框架的(性能差),所以需要排除logback,不然会出现jar依赖冲突的报错 -->
   <exclusions><!-- 去掉springboot默认配置 -->
      <exclusion>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-logging</artifactId>
      </exclusion>
   </exclusions>
</dependency>
<dependency> <!-- 引入log4j2依赖 -->
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>


2)配置日志文件

在resources目录下,使用log4j2.xml文件

3)其他特殊处理

在application.properties文件中配置

# 不显示thymeleaf日志
logging.level.org.thymeleaf=info

六 发布项目

1 修改打包方式为war

<packaging>war</packaging>

2 修改启动类

@SpringBootApplication
@MapperScan("com.rr.springboot04ajax.dao")
public class Springboot04AjaxApplication extends SpringBootServletInitializer{

   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(Springboot04AjaxApplication.class);
   }
   public static void main(String[] args) {
      SpringApplication.run(Springboot04AjaxApplication.class, args);
   }

}


3 通过maven打包

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NHxtmEI3-1576815335284)(file:///D:\内网通\讲师资料\课件\15_3_springboot\笔记\bootpic\wpsD476.tmp.jpg)]

一般可以先clean,再package

4 将war包拷贝到webapps目录下

七 springboot中集成swagger

现在开发,很多采用前后端分离的模式,前端只负责调用接口,进行渲染,前端和后端的唯一联系,变成了API接口。因此,API文档变得越来越重要。swagger是一个方便我们更好的编写API文档的框架,而且swagger可以模拟http请求调用。

1 导入jar

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

2 配置类

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 创建API应用
     * apiInfo() 增加API相关信息
     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
     * 本例采用指定扫描的包路径来定义指定要建立API的目录。
     *
     * @return
     */
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.rr.controller"))
                .paths(PathSelectors.any())
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .build();
    }

    /**
     * 创建该API的基本信息(这些基本信息会展现在文档页面中)
     * 访问地址:http://项目实际地址/swagger-ui.html
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测试 APIs")
                .description("测试api接口文档")
                .termsOfServiceUrl("http://www.qfedu.com")
                .version("1.0")
                .build();
    }

}
 

3 调用

http://项目实际地址/swagger-ui.html

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cY9btvF8-1576815335284)(file:///D:\内网通\讲师资料\课件\15_3_springboot\笔记\bootpic\wpsD496.tmp.jpg)]

4 swagger注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

@Api:修饰整个类,描述Controller的作用

例如:@Api(“用户管理API”)

@ApiOperation:描述一个类的一个方法,或者说一个接口

例如:@ApiOperation(value=“获取用户详细信息”, notes=“根据id来获取用户详细信息”)

@ApiParam:单个参数描述,修饰属性

@ApiModel:用对象来接收参数 ,修饰类

@ApiModelProperty:用对象接收参数时,描述对象的一个字段

@ApiResponse:HTTP响应其中1个描述

@ApiResponses:HTTP响应整体描述,一般描述错误的响应

@ApiIgnore:使用该注解忽略这个API

@ApiError :发生错误返回的信息

@ApiImplicitParam:一个请求参数,用在方法上

例如:@ApiImplicitParam(name = “id”, value = “用户ID”, required = true, dataType = “Integer”, paramType = “path”)

@ApiImplicitParams:多个请求参数

例如:@ApiImplicitParams({

​ @ApiImplicitParam(),

​ @ApiImplicitParam()

​ })

针对返回值,使用泛型表示,比如

public class JsonResult{

。。。

}

八 热部署处理

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
   <optional>true</optional>
</dependency>


<plugin>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-maven-plugin</artifactId>
   <configuration>
      <fork>true</fork>
   </configuration>
</plugin>

手动:

修改完类文件后,ctrl+f9,构建整个项目, 或者针对某个文件ctrl+shift+f9,构建某个类,就会重新启动

自动:

勾选 自动编译选项

Ctrl+alt+shift+/ 选择registry

勾选[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BoS995Mx-1576815335285)(file:///D:\内网通\讲师资料\课件\15_3_springboot\笔记\bootpic\wps601.tmp.png)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值