Spring Boot

前言

  • Spring Boot 是基于 Spring 的一套快速开发整合包。

  • 它的目的在于实现自动配置,降低项目搭建的复杂度,开发人员只用关心提供业务功能就行了,如需要搭建一个接口服务,通过 Spring Boot,几行代码即可实现。

  • Spring Boot 相当于一个大的框架,里面包含了包括 Spring 在内的其他东西,Spring MVC 又仅仅是 Spring 当中处理 Web 层请求的一个模快,所以,整体上来说,三者之间的关系大概为:Spring Boot > Spring > Spring MVC。

  • Spring 官网

  • Spring Boot 那些事

  • Spring Boot 2.02 官方参考指南

  • Spring Boot 快速入门

  • 若依管理系统

  • 若依开发文档

1、Spring Boot

  • Spring Boot(英文中是 “引导” 的意思),是用来简化 Spring 应用的搭建到开发的过程。

  • 应用开箱即用,只要通过 “just run”(可能是 java -jar 或 tomcat 或 maven 插件 run 或 shell 脚本),就可以启动项目。

  • 二者,Spring Boot 只要很少的 Spring 配置文件(例如那些 xml,property)。

  • 因为 “习惯优先于配置” 的原则,使得 Spring Boot 在快速开发应用和微服务架构实践中得到广泛应用。

1.1 配置

  • pom.xml 配置文件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    <?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>

    <groupId>com.how2java</groupId>
    <artifactId>springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot</name>
    <description>springboot</description>

    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.9.RELEASE</version>
    </parent>

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

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

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

    </project>
  • 启动类

    • 运行其主方法就会启动 tomcat,默认端口是 8080。
1
2
3
4
5
6
7
8
9
10
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
  • 控制器类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    @RestController
    public class HelloController {

    @RequestMapping("/hello")
    public String hello() {
    return "Hello Spring Boot!";
    }
    }
  • 关键字

关键字 介绍
@SpringBootApplication 表示这是一个 Spring Boot 应用
@RestController 一个普通的控制器,是 @ResponseBody 和 @Controller 的缩写
@RequestMapping 网络请求

1.1.1 Eclipse 项目

  • Eclipse 提供了一个专门开发 Spring Boot 的插件叫做 Spring Tool Suite,这个插件的安装是使用国外的源,安装很卡。

  • 而 Spring Boot 应用,本质上是一个 Java 程序,其采用的风格是 maven 风格,所以又是一个 Maven 项目,按照 maven 项目的方式创建就行了。

  • Eclipse 导入项目

1.1.2 Idea 项目

  • Idea 本身自带对 Spring Boot 支持的插件,不像 Eclipse 那样,要用插件还需要从第三方安装,而且很缓慢。

  • Idea 导入项目

1.2 部署

  • Spring Boot 本质上是一个 Java 应用程序,部署会采用两种方式。

    • 全部打包成一个 jar 包
    • 或者打包成一个 war 包

1.2.1 jar 包和 war 包的区别

  • Jar 包、war 包在文件结构上,二者并没有什么不同,它们都采用 zip 或 jar 档案文件压缩格式。但是它们的使用目的有所区别:

  • jar 包

    • Jar 文件(扩展名为 .Jar,Java Application Archive)包含 Java 类的普通库、资源(resources)、辅助文件(auxiliary files)等。
    • jar 包是 java 打的包,一般只是包括一些编译后 class 文件和一些部署文件,在声明了 Main_class 之后是可以用 java 命令运行的。
    • jar 包通常是开发时要引用通用类,打成包便于存放管理。
  • war 包

    • War 文件(扩展名为 .War,Web Application Archive)包含全部 Web 应用程序。在这种情形下,一个 Web 应用程序被定义为单独的一组文件、类和资源,用户可以对 war 文件进行封装,并把它作为小型服务程序(servlet)来访问。
    • war 包可以理解为 javaweb 打的包,是一个 web 模块,包括写的代码编译成的 class 文件,依赖的包,配置文件,所有的网站页面,包括 html,jsp 等等。一个 war 包可以理解为是一个 web 项目,里面是项目的所有东西。
    • war 包需要发布到一个容器里面,拿 Tomcat 来说, 将 war 文件包放置它的 \webapps\ 目录下,启动 Tomcat, 这个包可以自动进行解压,也就是你的 web 目录,相当于发布了。
    • war 是 Sun 提出的一种 Web 应用程序格式,与 jar 类似,也是许多文件的一个压缩包。这个包中的文件按一定目录结构来组织:通常其根目录下包含有 Html 和 Jsp 文件或者包含这两种文件的目录,另外还会有一个 WEB-INF 目录,这个目录很重要。通常在 WEB-INF 目录下有一个 web.xml 文件和一个 classes 目录,web.xml 是这个应用的配置文件,而 classes 目录下则包含编译好的 Servlet 类和 Jsp 或 Servlet 所依赖的其它类(JavaBean)。

1.2.2 jar 包方式

  • 打包成 jar 包

    1
    2
    # cd 到项目根目录下,打包
    $ mvn package
  • 运行该 jar 包

    1
    2
    3
    4
    5
    # 运行 jar 包
    $ java -jar target/springboot-0.0.1-SNAPSHOT.jar

    # 后台运行 jar 包,输出日志到文件 nohup.out 中
    $ nohup java -jar target/springboot-0.0.1-SNAPSHOT.jar >nohup.out 2>&1 &

1.2.3 war 包方式

  • 修改 Application 类

    • 新加 @ServletComponentScan 注解。并且继承 SpringBootServletInitializer。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      import org.springframework.boot.SpringApplication;
      import org.springframework.boot.autoconfigure.SpringBootApplication;
      import org.springframework.boot.builder.SpringApplicationBuilder;
      import org.springframework.boot.web.servlet.ServletComponentScan;
      import org.springframework.boot.web.support.SpringBootServletInitializer;

      @SpringBootApplication
      @ServletComponentScan
      public class Application extends SpringBootServletInitializer {

      @Override
      protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
      return application.sources(Application.class);
      }

      public static void main(String[] args) {
      SpringApplication.run(Application.class, args);
      }
      }
  • 修改 pom.xml 配置文件

    • 新加打包成 war 的声明。

      1
      <packaging>war</packaging>                                 <!-- 设置打包类型,打包成 war 包 -->
    • spring-boot-starter-tomcat 修改为 provided 方式,以避免和独立 tomcat 容器的冲突。provided 表示只在编译和测试的时候使用,打包的时候就没它了。

      1
      2
      3
      4
      5
      <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
      <scope>provided</scope> <!-- 设置只在编译和测试的时候使用 -->
      </dependency>
    • 新加编译插件。

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      <build>
      <plugins>
      <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <executions>
      <execution>
      <goals>
      <goal>repackage</goal>
      </goals>
      </execution>
      </executions>
      <configuration>
      <finalName>helloWorld</finalName> <!-- 设置打包后的 war 包名称-->
      </configuration>
      </plugin>
      <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId> <!-- 添加 war 包打包插件 -->
      <configuration>
      <failOnMissingWebXml>false</failOnMissingWebXml>
      </configuration>
      </plugin>
      </plugins>
      </build>
  • 打包成 war 包

    • 打包

      1
      2
      # cd 到项目根目录下,打包
      $ mvn package
  • 重命名 war 包,部署

    • 如果用 springboot-0.0.1-SNAPSHOT.war 这个文件名部署,那么访问的时候就要在路径上加上 springboot-0.0.1-SNAPSHOT。
    • 把这个文件重命名为 ROOT.war,然后把它放进 Tomcat 的 webapps 目录下。
    • ROOT.war 并不是指访问的时候要使用 /ROOT/hello,而是直接使用 /hello 进行访问,ROOT 表示根路径。

1.3 热部署

  • Spring Boot 提供了热部署的方式,当发现任何类发生了改变,马上通过 JVM 类加载的方式,加载最新的类到虚拟机中。这样就不需要重新启动也能看到修改后的效果了。

  • 做法很简单,在 pom.xml 中新增加一个依赖和一个插件就行了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <dependencies>

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional> <!-- 这个需要为 true 热部署才有效 -->
    </dependency>

    </dependencies>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <build>
    <plugins>

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

    </plugins>
    </build>
  • 在开发过程中,如果我们修改了某些 java 文件,我们可能需要重启下项目来观看修改后的结果,如果使用 spring-boot-devtools,当 classpath 中有文件变动时候,devtools 会自动帮你重启服务器。

  • 注意,这里的重启的条件是 classpath 的文件要有变化,如果你在使用 IDEA 开发的话,请勾选 “Build project automatically” 选项,如下图示所示,否则你需要重新 build 项目来使重启生效。

1.4 JSP 支持

  • Spring Boot 的默认视图支持是 Thymeleaf

  • pom.xml 增加对 JSP 支持。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <!-- servlet 依赖 -->
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    </dependency>
    <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    </dependency>

    <!-- tomcat 的支持 -->
    <dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
  • 在 src/main/resources 目录下增加 application.properties 文件,用于视图重定向 jsp 文件的位置。

    1
    2
    spring.mvc.view.prefix=/WEB-INF/jsp/
    spring.mvc.view.suffix=.jsp
  • 把 @RestController 改为 @Controller。

  • 这时返回 “hello” 就不再是字符串,而是根据 application.properties 中的视图重定向,到 /WEB-INF/jsp 目录下去寻找 hello.jsp 文件。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    @Controller
    public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model m) {
    m.addAttribute("now", DateFormat.getDateTimeInstance().format(new Date()));
    return "hello";
    }
    }

1.5 端口和上下文路径

  • 可以通过修改 application.properties,修改访问的端口和上下文路径

    1
    2
    server.port=8888
    server.context-path=/test

1.6 配置切换

  • 有时候在本地测试是使用 8080 端口,可是上线使用的又是 80 端口。此时就可以通过多配置文件实现多配置支持与灵活切换

  • 多配置文件

    • 核心配置文件:application.properties
    • 开发环境用的配置文件:application-dev.properties
    • 生产环境用的配置文件:application-pro.properties

    • application.properties

      1
      2
      3
      spring.mvc.view.prefix=/WEB-INF/jsp/
      spring.mvc.view.suffix=.jsp
      spring.profiles.active=pro
    • application-dev.properties

      1
      2
      server.port=8080
      server.context-path=/test
    • application-pro.properties

      1
      2
      server.port=80
      server.context-path=/
  • 可以通过 application.properties 里的 spring.profiles.active=pro 灵活地来切换使用哪个环境。

    1
    spring.profiles.active=pro
  • 不仅可以通过修改 application.properties 文件进行切换,还可以在部署环境下,指定不同的参数来确保生产环境总是使用的希望的那套配置。

    1
    2
    3
    java -jar target/springboot-0.0.1-SNAPSHOT.jar --spring.profiles.active=pro

    java -jar target/springboot-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

1.7 配置文件 yml

  • 在 Spring Boot 里配置文件除了使用 .properties 外,还支持 yml 格式。

    1
    2
    3
    4
    5
    6
    7
    8
    spring:
    mvc:
    view:
    prefix: /WEB-INF/jsp/
    suffix: .jsp
    server:
    port: 8888
    context-path: /test
  • 在 application.yml 文件书写注意

    • 不同 “等级” 用冒号隔开。
    • 次等级的前面是空格,不能使用制表符 (tab)。
    • 冒号之后如果有值,那么冒号和值之间至少有一个空格,不能紧贴着。
  • 要么用 application.properties 要么用 application.yml,不要都用。

2、启动器 Starter

  • Spring Boot starter 机制

    • Spring Boot 抛弃以前繁杂的配置,将其统一集成进 starter,应用者只需要在 maven 中引入 starter 依赖,Spring Boot 就能自动扫描到要加载的信息并启动相应的默认配置。

    • starter 让我们摆脱了各种依赖库的处理,需要配置各种信息的困扰。Spring Boot 会自动通过 classpath 路径下的类发现需要的 Bean,并注册进 IOC 容器。Spring Boot 提供了针对日常企业应用研发各种场景的 spring-boot-starter 依赖模块。

  • 自定义 starter

    • 在我们的日常开发工作中,经常会有一些独立于业务之外的配置模块,我们经常将其放到一个特定的包下,然后如果另一个工程需要复用这块功能的时候,需要将代码硬拷贝到另一个工程,重新集成一遍,麻烦至极。

    • 如果我们将这些可独立于业务代码之外的功配置模块封装成一个个 starter,复用的时候只需要将其在 pom 中引用依赖即可,Spring Boot 为我们完成自动装配。

  • starter 命名规范

    1
    2
    3
    4
    5
    6
    7
    Spring Boot 官方命名方式
    格式:spring-boot-starter-{模块名}
    举例:spring-boot-starter-web

    自定义命名方式
    格式:{模块名}-spring-boot-starter
    举例:mystarter-spring-boot-starter
  • Spring Boot 基本应用启动器

启动器 功能
spring-boot-starter 这是 Spring Boot 的核心启动器,包含了自动配置、日志和 YAML
spring-boot-starter-actuator 帮助监控和管理应用
spring-boot-starter-amqp 通过 spring-rabbit 来支持 AMQP 协议(Advanced Message Queuing Protocol)
spring-boot-starter-aop 支持面向切面的编程,即 AOP,包括 spring-aop 和 AspectJ
spring-boot-starter-artemis 通过 Apache Artemis 支持 JMS的API(Java Message Service API)
spring-boot-starter-batch 支持 Spring Batch,包括 HSQLDB 数据库
spring-boot-starter-cache 支持 Spring 的 Cache 抽象
spring-boot-starter-cloud-connectors 支持 Spring Cloud Connectors,简化了在像 Cloud Foundry 或 Heroku 这样的云平台上连接服务
spring-boot-starter-data-elasticsearch 支持 ElasticSearch 搜索和分析引擎,包括 spring-data-elasticsearch
spring-boot-starter-data-gemfire 支持 GemFire 分布式数据存储,包括 spring-data-gemfire
spring-boot-starter-data-jpa 支持 JPA(Java Persistence API),包括 spring-data-jpa、spring-orm、Hibernate
spring-boot-starter-data-mongodb 支持 MongoDB 数据,包括 spring-data-mongodb
spring-boot-starter-data-rest 通过 spring-data-rest-webmvc,支持通过 REST 暴露 Spring Data 数据仓库
spring-boot-starter-data-solr 支持 Apache Solr 搜索平台,包括 spring-data-solr
spring-boot-starter-freemarker 支持 FreeMarker 模板引擎
spring-boot-starter-groovy-templates 支持 Groovy 模板引擎
spring-boot-starter-hateoas 通过 spring-hateoas 支持基于 HATEOAS 的 RESTful Web 服务
spring-boot-starter-hornetq 通过 HornetQ 支持 JMS
spring-boot-starter-integration 支持通用的 spring-integration 模块
spring-boot-starter-jdbc 支持 JDBC 数据库
spring-boot-starter-jersey 支持 Jersey RESTful Web 服务框架
spring-boot-starter-jta-atomikos 通过 Atomikos 支持 JTA 分布式事务处理
spring-boot-starter-jta-bitronix 通过 Bitronix 支持 JTA 分布式事务处理
spring-boot-starter-mail 支持 javax.mail 模块
spring-boot-starter-mobile 支持 spring-mobile
spring-boot-starter-mustache 支持 Mustache 模板引擎
spring-boot-starter-quartz 任务调度框架,在预先确定的时间到达时,负责执行(或者通知)其他软件组件的系统,也就是定时执行一个任务
spring-boot-starter-redis 支持 Redis 键值存储数据库,包括 spring-redis
spring-boot-starter-security 支持 spring-security
spring-boot-starter-social-facebook 支持 spring-social-facebook
spring-boot-starter-social-linkedin 支持 pring-social-linkedin
spring-boot-starter-social-twitter 支持 pring-social-twitter
spring-boot-starter-test 支持常规的测试依赖,包括 JUnit、Hamcrest、Mockito 以及 spring-test 模块
spring-boot-starter-thymeleaf 支持 Thymeleaf 模板引擎,包括与 Spring 的集成
spring-boot-starter-validation 参数校验
spring-boot-starter-velocity 支持 Velocity 模板引擎
spring-boot-starter-web 支持全栈式 Web 开发,包括 Tomcat 和 spring-webmvc
spring-boot-starter-websocket 支持 WebSocket 开发
spring-boot-starter-ws 支持 Spring Web Services
面向生产环境的启动器
spring-boot-starter-actuator 增加了面向产品上线相关的功能,比如测量和监控,帮助监控和管理应用
spring-boot-starter-remote-shell 增加了远程 ssh shell 的支持
替换技术的启动器
spring-boot-starter-jetty 引入了 Jetty HTTP 引擎(用于替换 Tomcat)
spring-boot-starter-log4j 支持 Log4J 日志框架
spring-boot-starter-logging 引入了 Spring Boot 默认的日志框架 Logback
spring-boot-starter-tomcat 引入了 Spring Boot 默认的 HTTP 引擎 Tomcat
spring-boot-starter-undertow 引入了 Undertow HTTP 引擎(用于替换 Tomcat)

3、持久层支持

  • 修改 application.properties,新增数据库链接必须的参数。

    1
    2
    3
    4
    5
    spring.datasource.url=jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8
    spring.datasource.username=root
    spring.datasource.password=admin
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    spring.jpa.properties.hibernate.hbm2ddl.auto=update

3.1 JPA

  • JPA(Java Persistence API)是 Sun 官方提出的 Java 持久化规范,用来方便操作数据库。

  • 真正干活的可能是 Hibernate,TopLink 等等实现了 JPA 规范的不同厂商,默认是 Hibernate

  • 增加对 mysql 和 jpa 的支持

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    <dependencies>
    <!-- mysql -->
    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
    </dependency>

    <!-- jpa -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    </dependencies>
  • CRUD + 分页

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    @Autowired CategoryDAO categoryDAO;

    @RequestMapping("/listCategory")

    public String listCategory(Model m,
    @RequestParam(value = "start", defaultValue = "0") int start,
    @RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
    start = start<0?0:start;

    Sort sort = new Sort(Sort.Direction.DESC, "id");
    Pageable pageable = new PageRequest(start, size, sort);
    Page<Category> page =categoryDAO.findAll(pageable);

    m.addAttribute("page", page);
    return "listCategory";
    }

    @RequestMapping("/addCategory")
    public String addCategory(Category c) throws Exception {
    categoryDAO.save(c);
    return "redirect:listCategory";
    }

    @RequestMapping("/deleteCategory")
    public String deleteCategory(Category c) throws Exception {
    categoryDAO.delete(c);
    return "redirect:listCategory";
    }

    @RequestMapping("/updateCategory")
    public String updateCategory(Category c) throws Exception {
    categoryDAO.save(c);
    return "redirect:listCategory";
    }

    @RequestMapping("/editCategory")
    public String ediitCategory(int id,Model m) throws Exception {
    Category c= categoryDAO.getOne(id);
    m.addAttribute("c", c);
    return "editCategory";
    }
  • JPA 条件查询是不需要写 SQL 语句的,只需要在 dao 接口里按照规范的命名定义对应的方法名,及可达到查询相应字段的效果了。

    • 虽然 JPA 没有自己手动写 sql 语句,但是通过反射获取自定义的接口方法里提供的信息,就知道用户希望根据什么条件来查询了。
    • 然后 JPA 底层再偷偷摸摸地拼装对应的 sql 语句,丢给数据库,就达到了条件查询的效果啦。
  • JPA 条件查询规范

关键词 举例 生成的 JPQL 语句片段
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is
Equals
findByFirstname
findByFirstnameIs
findByFirstnameEquals
… where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull
NotNull
findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection ages) … where x.age in ?1
NotIn findByAgeNotIn(Collection age) … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)

3.2 Mybatis

  • Mybatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。

  • Mybatis - 注解方式

    1
    2
    3
    4
    5
    6
    7
    8
    package com.how2java.springboot.mapper;

    @Mapper
    public interface CategoryMapper {

    @Select("select * from category_ ")
    List<Category> findAll();
    }
  • Mybatis - xml 方式

    1
    2
    3
    4
    5
    6
    7
    8
    <?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.how2java.springboot.mapper.CategoryMapper">
    <select id="findAll" resultType="Category">
    select * from category_
    </select>
    </mapper>
  • 使用 Mybatis 做一个完整的 CRUD 和分页。

    1
    2
    3
    4
    5
    6
    <!-- pagehelper -->
    <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>4.1.6</version>
    </dependency>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    @Configuration
    public class PageHelperConfig {

    @Bean
    public PageHelper pageHelper() {
    PageHelper pageHelper = new PageHelper();
    Properties p = new Properties();
    p.setProperty("offsetAsPageNum", "true");
    p.setProperty("rowBoundsWithCount", "true");
    p.setProperty("reasonable", "true");
    pageHelper.setProperties(p);
    return pageHelper;
    }
    }

3.3 SQLite

  • SQLite 是一种轻型的嵌入式数据库,它占用资源非常低,在嵌入式设备中,可能需要几百 K 的内存数据就够了。

  • SQLite 它是跑在 JVM 里面的,所以不需要像 mysql 那样得独立安装配置,而是直接拿来就用。

    1
    2
    3
    4
    5
    <dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <scope>runtime</scope>
    </dependency>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    spring.jpa.database-platform=com.how2java.sqlite.SQLiteDialect

    # 表结构由 hibernate 根据实体类来帮你创建
    spring.jpa.generate-ddl=true

    # 自动根据 Entity 配置创建表
    spring.jpa.hibernate.ddl-auto=update

    # 数据库文件位置
    spring.datasource.url=jdbc:sqlite:how2j.db

    # 驱动名称
    spring.datasource.driver-class-name=org.sqlite.JDBC

4、其他

4.1 单元测试

  • 有时候呢,Spring Boot 里要做单元测试,而不是直接跑起来。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
    </dependency>

    <!-- Spring Boot test -->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    import java.util.List;

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    import com.how2java.springboot.Application;
    import com.how2java.springboot.dao.CategoryDAO;
    import com.how2java.springboot.pojo.Category;

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Application.class)
    public class TestJPA {

    @Autowired CategoryDAO dao;

    @Test
    public void test() {
    List<Category> cs = dao.findAll();
    for (Category c : cs) {
    System.out.println("c.getName():"+ c.getName());
    }
    }
    }

4.2 上传文件

  • 默认上传文件的大小是 1Mb。

    1
    2
    spring.http.multipart.maxFileSize=100Mb
    spring.http.multipart.maxRequestSize=100Mb
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String upload(HttpServletRequest req, @RequestParam("file") MultipartFile file,Model m) {
    try {
    String fileName = System.currentTimeMillis() + file.getOriginalFilename();
    String destFileName = req.getServletContext().getRealPath("") + "uploaded" + File.separator+fileName;

    File destFile = new File(destFileName);
    destFile.getParentFile().mkdirs();
    file.transferTo(destFile);

    m.addAttribute("fileName", fileName);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    return "上传失败," + e.getMessage();
    } catch (IOException e) {
    e.printStackTrace();
    return "上传失败," + e.getMessage();
    }

    return "showImg";
    }

4.3 Restful

  • Restful 风格使用同一个 url,但是约定不同的 method 来实施不同的业务。
CRUD 传统风格 url method Restful 风格 url method
增加 /addCategory?name=xxx POST
/categories POST
删除 /deleteCategory?id=123 GET
/categories/123 DELETE
修改 /updateCategory?id=123&name=yyy POST
/categories/123 PUT
获取 /getCategory?id=123 GET
/categories/123 GET
查询 /listCategory GET
/categories GET

4.4 JSON

  • JSON(JavaScript Object Notation)JavaScript 对象表示法,是一种存储数据的方式。

    1
    2
    3
    4
    5
    6
    7
    var url = "category/10";
    $.get(
    url,
    function(result) {
    console.log(result);
    }
    );
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    var url = "category";

    var id = document.getElementById('id').value;
    var name = document.getElementById('name').value;
    var category = {"id": id, "name": name};
    var jsonData = JSON.stringify(category);

    $.ajax({
    type: "put",
    url: url,
    data: jsonData,
    dataType: "json",
    contentType: "application/json; charset=UTF-8",
    success: function(result) {
    console.log(result);
    }
    });

4.5 Redis

  • Redis(REmote DIctionary Server)是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,是跨平台的非关系型数据库

    1
    2
    3
    4
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    # Redis 数据库索引(默认为 0)
    spring.redis.database=0

    # Redis 服务器地址
    spring.redis.host=127.0.0.1

    # Redis 服务器连接端口
    spring.redis.port=6379

    # Redis 服务器连接密码(默认为空)
    spring.redis.password=

    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.pool.max-active=10

    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.pool.max-wait=-1

    # 连接池中的最大空闲连接
    spring.redis.pool.max-idle=8

    # 连接池中的最小空闲连接
    spring.redis.pool.min-idle=0

    # 连接超时时间(毫秒)
    spring.redis.timeout=0

    # 让 hibernate 的 sql 语句显示出来,这样才知道到底是通过 Redis 取到的数据,还是依然是从数据库取到的数据
    spring.jpa.show-sql=true

4.6 ElasticSearch

  • ElasticSearch 基于 Lucene 进行了封装,提供了更为便利的访问和调用。

  • Spring Boot 有一个 spring data 组件,可以用来连接各种数据源。

  • 用来连接 ElasticSearch 的是 spring-data-elasticsearch。

5、Spring Cloud

  • Spring Cloud 是一个基于 Spring Boot 实现的云应用开发工具。

  • Spring Cloud 包含了多个子项目,比如:Spring Cloud Netflix 、Spring Cloud Config、Spring Cloud Stream、Spring Cloud Bus、Spring Cloud Sleuth 等项目。

文章目录
  1. 1. 前言
  2. 2. 1、Spring Boot
    1. 2.1. 1.1 配置
      1. 2.1.1. 1.1.1 Eclipse 项目
      2. 2.1.2. 1.1.2 Idea 项目
    2. 2.2. 1.2 部署
      1. 2.2.1. 1.2.1 jar 包和 war 包的区别
      2. 2.2.2. 1.2.2 jar 包方式
      3. 2.2.3. 1.2.3 war 包方式
    3. 2.3. 1.3 热部署
    4. 2.4. 1.4 JSP 支持
    5. 2.5. 1.5 端口和上下文路径
    6. 2.6. 1.6 配置切换
    7. 2.7. 1.7 配置文件 yml
  3. 3. 2、启动器 Starter
  4. 4. 3、持久层支持
    1. 4.1. 3.1 JPA
    2. 4.2. 3.2 Mybatis
    3. 4.3. 3.3 SQLite
  5. 5. 4、其他
    1. 5.1. 4.1 单元测试
    2. 5.2. 4.2 上传文件
    3. 5.3. 4.3 Restful
    4. 5.4. 4.4 JSON
    5. 5.5. 4.5 Redis
    6. 5.6. 4.6 ElasticSearch
  6. 6. 5、Spring Cloud
隐藏目录