Spring Boot

Spring Boot

Spring 全家桶非常重要的一个模块,通过 Spring Boot 可以快速搭建一个基于 Spring 的 Java 应用程序,Spring Boot 对常用的第三方库提供了配置方案,可以很好地和 Spring 进行整合,MyBatis、Spring Data JPA 等,可以一键式搭建功能完备的 Java 企业级应用。

Spring Boot 的优势

  • 不需要任何 XML 配置文件。
  • 内嵌 Web 服务器,可以直接启动。
  • 默认支持 JSON 数据,不需要做额外配置。
  • 支持 RESTful 风格
  • 使用一个配置文件(非 XML、propertis、YAML)可以配置所有的个性化信息

Spring Boot 就是一个可以用很少的配置快速搭建 Spring 应用的框架,并且可以自动集成主流的 Java 技术栈。

创建 Spring Boot 应用

  • 在线创建工程

https://start.spring.io/

  • IDEA Spring Initializr

  • 手动创建 Spring Boot 工程

1、创建 Maven 工程。

2、pom.xml 中添加 Spring Boot 相关依赖。

在 parent 标签中配置 spring-boot-starter-parent 依赖,相当于给整个工程添加了一个 Spring Boot 的父依赖,其他模块直接在继承父依赖的基础上添加特地依赖即可,比如要集成 Web MVC 组件,直接添加 spring-boot-starter-web 依赖即可。

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

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

3、创建 Handler

package com.southwind.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloHandler {

    @GetMapping("/index")
    public String index(){
        return "Hello World";
    }

}

4、创建 Spring Boot 启动类 Application。

package com.southwind;

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);
    }
}

Application 是整个 Spring Boot 应用的入口,可以看到在类定义处添加了一个 @SpringBootApplicaiton 注解,这个注解是 Spring Boot 的核心,它开启了 Spring Boot 的自动化配置,开发者可以使用自定义配置来覆盖自动化配置,同时它完成了自动扫包,默认的范围是该类所在包的所有子包,当然也包括所在包本身,实际开发中我们应该将 Application 放置在根节点。

要启动 Spring Boot 应用,直接运行启动类 Application 的 main 方法即可,会自动将项目部署到内嵌的 Tomcat 中,并启动 Tomcat。

自定义 Banner

1、在 resources 路径下创建 banner.txt。

在第三方网站自行编辑自定义 banner:http://patorjk.com/software/taag

Spring Boot 可以简化大部分的配置,但是需要开发者自定义的配置用两种格式来定义,propertis、YAML

  • properties
server.port=8181

application.proerties

#tomcat端口
server.port=8181
#项目访问路径
server.servlet.context-path=/test
#cookie失效时间,单位为秒
server.servlet.session.cookie.max-age=100
#session失效时间,单位为秒
server.servlet.session.timeout=100
#编码格式
server.tomcat.uri-encoding=UTF-8
  • YAML 格式

YAML 是不同于 properties 的另外一种文本格式,同样可以用来写配置文件,Spring Boot 默认支持 YAML 格式,YAML 的优点在于编写简单,结构清晰,利用缩进的形式来表示层级关系。相比于 properties,可以进一步简化配置文件的编写。

server:
  port: 8181
  servlet:
    context-path: /test
    session:
      cookie:
        max-age: 100
      timeout: 100
  tomcat:
    uri-encoding: UTF-8

同时存在两种格式的配置文件时,properties 的优先级更高。

配置文件的位置有四个地方可以选择

  • config
  • resources
  • resources/config
  • 根目录

config>根目录>resources/config>resources

Handler 读取配置文件信息

package com.southwind.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloHandler {

    @Value("${server.port}")
    private String port;

    @GetMapping("/index")
    public String index(){
        return "端口是"+this.port;
    }

}

Spring Boot 整合视图层技术

  • JSP

Java Server Page

1、pom.xml

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

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

  <dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
  </dependency>
</dependencies>

2、创建 Handler,返回 JSP 视图

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloHandler {

    @GetMapping("/index")
    public String index(){
        return "index";
    }
}

3、application.yml

spring:
  mvc:
    view:
      prefix: /
      suffix: .jsp

4、Application

package com.southwind;

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);
    }
}
  • Thymeleaf

Spring Boot 官方不推荐使用 JSP,而是建议使用 Thymeleaf。

什么Thymeleaf

Thymeleaf 事一个支持原生 HTML 文件的 Java 模版引擎,可以实现前后端分离的交互方式,可以直接将服务端的数据生成 HTML 格式,可以处理 XML、JavaScript、CSS 等格式。

Thymeleaf 最大的特点是既可以直接在浏览器打开,就像访问静态 HTML 页面一样,也可以结合服务端将业务数据填充进去看到动态生成的页面,Spring Boot 对 Thymeleaf 做了很好的集成。

1、创建 Maven 工程。

2、pom.xml

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

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

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

3、在 resources 路径创建 application.yml

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html

4、在 resources 路径下创建 templates 文件夹,在该路径下创建 HTML 文件。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>index</h1>
</body>
</html>

5、创建 Handler

package com.southwind.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloHandler {

    @GetMapping("/index")
    public String index(){
        return "index";
    }
}

6、创建启动类 Application

package com.southwind.controller;

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);
    }
}

如果需要将业务数据填充到 HTML 页面中,需要结合 Thymeleaf 模版标签来完成,HTML 页面中导入 Thymeleaf 模版标签的命名空间。

<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p th:text="${name}">Hello World</p>
</body>
</html>

Thymeleaf 常用标签

Thymeleaf 全部是嵌入到 HTML 标签内部去使用。

  • th:text

用于文本显示,将业务数据的值填充到 HTML 标签中

  • th:if

用来做条件判断,对业务数据的值进行判断,如果成立则显示内容,否则不显示。

@GetMapping("/index")
public ModelAndView index(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("index");
    modelAndView.addObject("score",90);
    return modelAndView;
}
<p th:if="${score>=90}">优秀</p>
<p th:if="${score<90}">良好</p>
  • th:unless

用来做条件判断,逻辑与 th:if 刚好相反,如果条件不成立显示,条件成立不显示。

  • th:switch th:case

th:switch、th:case 两个标签需要结合起来使用,用作多条件等值判断,逻辑与 Java 中的 switch-case 一致,当 switch 中的业务数据值等于某个 case 值时,就显示该 case 对应的内容。

@GetMapping("/index")
public ModelAndView index(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("index");
    modelAndView.addObject("id",2);
    return modelAndView;
}
<div th:switch="${id}">
  <p th:case="1">张三</p>
  <p th:case="2">李四</p>
  <p th:case="3">王五</p>
</div>
  • th:action

用来指定请求的 URL,相当于 form 表单中的 action 属性。

<form th:action="@{/login}" method="post">
    用户名:<input type="text" name="name"/><br/>
    密码:<input type="password" name="password"/><br/>
    <input type="submit" value="登录"/>
</form>
  • th:each
@GetMapping("/each")
public ModelAndView each(){
    List<User> list = new ArrayList<>();
    list.add(new User(1L,"张三",0));
    list.add(new User(2L,"李四",1));
    list.add(new User(3L,"王五",0));
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("list",list);
    return modelAndView;
}
<table>
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>年龄</th>
    </tr>
    <tr th:each="user:${list}">
        <td th:text="${user.id}"></td>
        <td th:text="${user.name}"></td>
        <td th:if="${user.gender == 1}"></td>
        <td th:if="${user.gender == 0}"></td>
    </tr>
</table>
  • th:value

用来给标签赋值

@GetMapping("/value")
public ModelAndView value(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("value","Spring Boot");
    return modelAndView;
}
<input type="text" th:value="${value}"/>
  • th:src

用来引入静态资源,相当于 HTML 原生标签 img、script 的 src 属性。

@GetMapping("/src")
public ModelAndView src(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("src","/1.png");
    return modelAndView;
}
<img th:src="${src}">
  • th:src
@GetMapping("/src")
public ModelAndView src(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("src","/1.png");
    return modelAndView;
}
${src}      //需要Handler将具体的路径传入到前端	
@{/1.png}   //Handler不需要传入具体的路径,只需要做映射,解析th标签

只要前端页面使用了 th,则必须通过 Handler 映射才能正确解析。

  • th:href
@GetMapping("/href")
public ModelAndView href(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("href","https://spring.io/projects/spring-boot");
    return modelAndView;
}
${href}						//需要Handler传值
@{http://www}			//不需要Handler传值

以上两种方式必须通过 Handler 映射才能解析,通 th:src

  • th:selected

用来给 HTML 元素设置选中,条件成立则选中,否则不选中。

@GetMapping("/selected")
public ModelAndView selected(){
  List<User> list = new ArrayList<>();
  list.add(new User(1L,"张三",1));
  list.add(new User(2L,"李四",0));
  list.add(new User(3L,"王五",1));
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("test");
  //        modelAndView.addObject("list",list);
  modelAndView.addObject("name","李四");
  return modelAndView;
}
<select>
  <!--        <option th:each="user:${list}" th:text="${user.name}" th:selected="${user.name == name}"></option>-->
  <option th:selected="${name=='张三'}">张三</option>
  <option th:selected="${name=='李四'}">李四</option>
  <option th:selected="${name=='王五'}">王五</option>
</select>
  • th:attr

用来给 HTML 标签的任意属性赋值。

@GetMapping("/attr")
public ModelAndView attr(){
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("attr","Spring Boot");
    return modelAndView;
}
<input th:attr="value=${attr}"/>

Thymeleaf 对象

Thymeleaf 支持直接访问 Servlet Web 原生资源,即 HttpServletRequest、HttpServletResponse、HttpSession、ServletContext 对象。

  • #request:获取 HttpServletRequest 对象

  • #response:获取 HttpServletResponse 对象

  • #session:获取 HttpSession 对象

  • #servletContext:获取 ServletContext 对象

@GetMapping("/servlet")
public String servlet(HttpServletRequest request){
    request.setAttribute("value","request");
    request.getSession().setAttribute("value","session");
    request.getServletContext().setAttribute("value","servletContext");
    return "test";
}
<p th:text="${#request.getAttribute('value')}"></p>
<p th:text="${#session.getAttribute('value')}"></p>
<p th:text="${#servletContext.getAttribute('value')}"></p>
<p th:text="${#response}"></p>

Thymeleaf 可以直接访问 session,通过 ${session.name} 可以直接取值。

@GetMapping("/session")
public ModelAndView session(HttpSession session){
    session.setAttribute("name","张三");
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("test");
    modelAndView.addObject("name","李四");
    return modelAndView;
}
<p th:text="${name}"></p>
<p th:text="${#request.getAttribute('name')}"></p>
<p th:text="${session.name}"></p>
<p th:text="${#session.getAttribute('name')}"></p>

Thymeleaf 内置对象

  • dates:日期格式化内置对象,参照 java.util.Date 的使用。
  • calendars:日期操作内置对象,参照 java.util.Calendar 的使用。
  • numbers:数字格式化内置对象。
  • strings:字符串格式化内置对象,参照 java.lang.String 的使用。
  • bools:boolean 类型内置对象。
  • arrays:数组操作内置对象,参照 java.utils.Arrays 的使用。
  • lists:List 集合内置对象,参照 java.util.List 的使用。
  • sets:Set 集合内置对象,参照 java.util.Set 的使用。
  • maps:Map 集合内置对象,参照 java.util.Map 的使用。
@GetMapping("/utility")
public ModelAndView utility(){
  ModelAndView modelAndView = new ModelAndView();
  modelAndView.setViewName("test");
  modelAndView.addObject("date",new Date());
  Calendar calendar = Calendar.getInstance();
  calendar.set(2019,1,1);
  modelAndView.addObject("calendar",calendar);
  modelAndView.addObject("number",0.06);
  modelAndView.addObject("string","Spring Boot");
  modelAndView.addObject("boolean",true);
  modelAndView.addObject("array", Arrays.asList("张三","李四","王五"));
  List<User> list = new ArrayList<>();
  list.add(new User(1L,"张三",1));
  list.add(new User(2L,"李四",0));
  list.add(new User(3L,"王五",1));
  modelAndView.addObject("list",list);
  Set<User> set = new HashSet<>();
  set.add(new User(1L,"张三",1));
  set.add(new User(2L,"李四",0));
  set.add(new User(3L,"王五",1));
  modelAndView.addObject("set",set);
  Map<Long,User> map = new HashMap<>();
  map.put(1L,new User(1L,"张三",1));
  map.put(2L,new User(2L,"李四",0));
  map.put(3L,new User(3L,"王五",1));
  modelAndView.addObject("map",map);
  return modelAndView;
}
date格式化:<span th:text="${#dates.format(date,'yyyy-MM-dd')}"></span><br/>
当前日期:<span th:text="${#dates.createToday()}"></span><br/>
当前时间:<span th:text="${#dates.createNow()}"></span><br/>
calendar格式化:<span th:text="${#calendars.format(calendar,'yyyy-MM-dd')}"></span><br/>
number百分比格式化:<span th:text="${#numbers.formatPercent(number,2,2)}"></span><br/>
string是否为空:<span th:text="${#strings.isEmpty(string)}"></span><br/>
string长度:<span th:text="${#strings.length(string)}"></span><br/>
string拼接:<span th:text="${#strings.concat('Hello World',string)}"></span><br/>
boolean是否为true:<span th:text="${#bools.isTrue(boolean)}"></span><br/>
arrays的长度:<span th:text="${#arrays.length(array)}"></span><br/>
arrays是否包含张三:<span th:text="${#arrays.contains(array,'张三')}"></span><br/>
list是否为空:<span th:text="${#lists.isEmpty(list)}"></span><br/>
list长度:<span th:text="${#lists.size(list)}"></span><br/>
set是否为空:<span th:text="${#sets.isEmpty(set)}"></span><br/>
set长度:<span th:text="${#sets.size(set)}"></span><br/>
map是否为空:<span th:text="${#maps.isEmpty(map)}"></span><br/>
map长度:<span th:text="${#maps.size(map)}"></span>

Spring Boot 整合持久层技术

Spring Boot 整合 MyBatis

Spring Boot 整合 Hibernate

Spring Boot 整合 Spring Data

Spring Boot 整合 JdbcTemplate

JdbcTemplate

JdbcTemplate 是 Spring 自带的 JDBC 模版组件,底层实现了对 JDBC 的封装,用法与 MyBatis 类似,开发者需要自定义 SQL 语句,JdbcTemplate 帮助开发者完成数据库连接,SQL 执行,以及结果集的解析。

JdbcTemplate 不足之处是灵活性不如 MyBatis,因为 MyBatis 的 SQL 定义在 XML 中,更有利用维护和扩展,但是 JdbcTemplate 是以硬编码的方式将 SQL 直接写在 Java 代码中,不利用扩展和维护。

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

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

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

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

Spring Boot 整合 JdbcTemplate

JdbcTemplate 对基本的 CRUD 操作提供了良好的支持,通过调用 query 和 update 方法即完成相关操作,其中 query 是用来做查询操作的,update 是用来做添加、删除、修改功能。

query

1、queryForObject(String sql,Object[] args,RowMapper rowMapper),查询一条记录,并且将结果集封装成 Java 对象。

2、query(String sql,RowMapper rowMapper),查询一组数据,并且将结果集封装成集合对象。

RowMapper 是一个接口,作用就是解析结果集,将 JDBC 查询出的 ResultSet 对象转换为对应的 Java 对象,在调用该对象时需要指定目标类的结构,泛型。

update

update(String sql, Object… args)

参数:1、要执行的 SQL 语句。2、可变参数 Object… args,满足参数的可变性。

客户端用?传参 key-value 形式将数据传给 Spring MVC 服务端,业务方法的形参列表不需要添加任何注解即可自动封装参数 Java 对象。

客户端传 JSON 格式数据,业务方法的形参列表需要添加 @RequestBody 注解,才能封装参数 Java 对象。

Spring Boot 整合 MyBatis

pom.xml

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

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

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

application.yml

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mybatis
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:/mapping/*.xml
  type-aliases-package: com.southwind.entity

Spring Boot 整合 Spring Data JPA

JPA、Spring Data JPA

Spring Data JPA 、JdbcTemplate

pom.xml

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

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

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

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.16</version>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true

StudentRepository

package com.southwind.repository;

import com.southwind.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student,Long> {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值